【发布时间】:2017-02-11 23:11:29
【问题描述】:
所以我不知道为什么,但我有一个自定义对象
struct Country {
id: Int,
name: String
}
//List of Countries
dataArray = [Country]()
//Error: "Cannot invoke filter with an arg list of type ((Country)) throws -> Bool
filteredArray = dataArray.filter({ (country) -> Bool in
let countryText:NSString = country.name as NSString
return (countryText.range(of: searchString, options: NSString.CompareOptions.caseInsensitive).location) != NSNotFound
})
如果 dataArray 是一个字符串列表,那么它会起作用,我只是不明白为什么,查看其他 SO 问题我返回一个布尔值
Filter array of custom objects in Swift
Swift 2.0 filtering array of custom objects - Cannot invoke 'filter' with an argument of list type
【问题讨论】:
-
您误解了
filter方法。因为该闭包的返回意味着:“我是否必须将该项目放入返回的数组中”?是的,它被添加了,否则,它没有被添加。然后由您根据项目进行适当的测试:就像在您的情况下对name属性进行测试一样。
标签: swift