0

So I'm not sure why, but I have a custom object

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
})

If dataArray was a list of Strings instead then it'll work, I just don't understand why, looking at other SO questions I am returning a boolean

Filter array of custom objects in Swift

Swift 2.0 filtering array of custom objects - Cannot invoke 'filter' with an argument of list type

Community
  • 1
  • 1
testinggnitset ser
  • 297
  • 1
  • 3
  • 17
  • You misunderstood the `filter` method. Because the return of that closure means: "Do I have to put that item in the returned array"? YES, it's added, else, it's not added. It's then up to you to do the proper test, according to the item: like doing the test on it's `name` property in your case. – Larme Feb 11 '17 at 23:23

1 Answers1

0

The problem in your filter closure is that it's of type ((Country)) throws -> Bool when it should be Country -> Bool

What this tells you is that your closure has some part in your code that may fail and throw an error. The compiler won't know how to interpret a fail so the closure can't throw an error.

Looking at your code, it may be due to the cast from a String to NSString. I tried to reproduce your code in my machine (Swift 3, Ubuntu 16.04) and it was failing there, in the cast. My solution was to use the constructor of NSString that recieves a String and it worked

Updated code:

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)

prints:

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

Hope it helps!

Federico Ojeda
  • 758
  • 7
  • 11