【问题标题】:Filter through custom array通过自定义数组过滤
【发布时间】: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


【解决方案1】:

你的过滤器闭包的问题是它的类型是((Country)) throws -> Bool,而它应该是Country -> Bool

这告诉你的是,你的闭包在你的代码中有一些部分可能会失败并抛出错误。编译器不知道如何解释失败,因此闭包不会抛出错误。

查看您的代码,可能是由于从String 转换为NSString。我试图在我的机器(Swift 3,Ubuntu 16.04)中重现您的代码,但在演员阵容中失败了。我的解决方案是使用NSString 的构造函数来接收String 并且它起作用了

更新代码:

struct Country {
  var id: Int
  var name: String
}

//List of Countries
let dataArray = [Country(id: 1, name: "aaaaaaa"), Country(id: 1, name: "bbbb")]

let filteredArray = dataArray.filter({ (country) -> Bool in
   let countryText: NSString = NSString(string: country.name)
   return (countryText.range(of: "aaa", options:   NSString.CompareOptions.caseInsensitive).location) != NSNotFound
})

print(filteredArray)

打印:

[helloWorld.Country(id: 1, name: "aaaaaaa")]

希望对您有所帮助!

【讨论】:

  • 谢谢,我太笨了,我意识到我的过滤数组没有正确的数据类型,所以你的例子帮助我弄清楚了谢谢
猜你喜欢
  • 2017-03-09
  • 2016-07-15
  • 1970-01-01
  • 2014-09-30
  • 1970-01-01
  • 2022-10-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多