我正在尝试从字典中过滤。
我的代码如下:
var newSimHistoryArr = [] as NSArray
if self.filterBy == kPending {
newSimHistoryArr = (dic["simHistory"] as! [AnyObject]).filter {
return $0 is NSDictionary
}
} else {
for a in dic["simHistory"] as! [AnyObject] {
if a is SimHistory {
newSimHistoryArr = (dic["simHistory"] as! [AnyObject]).filter {
return ($0 as! SimHistory).status == self.filterBy
}
break
}
}
}
在我将项目转换为 Swift 3 之前,它运行良好。
错误出现在以下几行:
newSimHistoryArr = (dic["simHistory"] as! [AnyObject]).filter{ return ($0 is NSDictionary)}
newSimHistoryArr = (dic["simHistory"] as! [AnyObject]).filter{ return ($0 as! SimHistory).status == self.filterBy}
错误是:
Cannot invoke 'filter' with an argument list of type '((AnyObject) throws -> Bool)'
我不知道出了什么问题......
最佳答案
将问题分解到最低级别,您可以在 Playground 中运行以下代码,它说明了错误:
var newSimHistoryArr = [] as NSArray
var oldHistory = ["book", "bath", "table"]
newSimHistoryArr = oldHistory.filter { $0.hasPrefix("b") }
错误消息是:
Playground execution failed: error: MyPlayground.playground:2:32: error: cannot invoke 'filter' with an argument list of type '((String) throws -> Bool)' newSimHistoryArr = oldHistory.filter { $0.hasPrefix("b") }
奇怪的是,错误的发生并不是因为过滤表达式本身,而是因为它被转换为的数据类型,即赋值左侧的数据类型。这对编译器来说是非常误导的。
将 newSimHistoryArr 的数据类型更改为兼容类型,一切正常。
var newSimHistoryArr:[String]
var oldHistory = ["book", "bath", "table"]
newSimHistoryArr = oldHistory.filter { $0.hasPrefix("b") }
或者更麻烦的形式:
var newSimHistoryArr = [] as NSArray
var oldHistory = ["book", "bath", "table"]
newSimHistoryArr = (oldHistory.filter { $0.hasPrefix("b") }) as NSArray
关于ios - Swift:无法使用 'filter' 类型的参数列表调用 '((AnyObject) throws -> Bool)',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40902274/