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

1
  • 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. Commented Feb 11, 2017 at 23:23

1 Answer 1

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!

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, I was being stupid and I realized my filteredArray didn't have the right datatype so your example helped me figure that out thanks

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.