Array<T>.first(where:) gives "cannot call value of non-function"

let a = ["a", "b", "c"]
let f = a.first(where:{ $0.caseInsensitiveCompare("B") })

Gives the error: Cannot call value of non-function type 'String?'


I know there is a property named first, but there's also an Array<T> method named first(where:), so what's happening? How to I call this? In the meantime I'll resort to using the equivalent index method, but that's a bit indirect, so that's a bit of a hack (not as clear to anyone reading my code).


Xcode 8.1

macOS 10.12.1

Answered by OOPer in 198398022

You need to pass a closure returning `Bool` to `Array.first(where:)`. (In fact it's a method of `Collection`, but it's not a big issue here.)

`String.caseInsensitiveCompare(_:)` returns `ComparisonResult`, not `Bool`.


I guess you may want to do something like this:

let a = ["a", "b", "c"]
let f = a.first(where:{ $0.caseInsensitiveCompare("B") == .orderedSame} )
print(f) //->Optional("b")


Or, if you just want a `Bool` result, you can use `contains(where:)`:

let g = a.contains(where: { $0.caseInsensitiveCompare("B") == .orderedSame})
print(g) //->true
Accepted Answer

You need to pass a closure returning `Bool` to `Array.first(where:)`. (In fact it's a method of `Collection`, but it's not a big issue here.)

`String.caseInsensitiveCompare(_:)` returns `ComparisonResult`, not `Bool`.


I guess you may want to do something like this:

let a = ["a", "b", "c"]
let f = a.first(where:{ $0.caseInsensitiveCompare("B") == .orderedSame} )
print(f) //->Optional("b")


Or, if you just want a `Bool` result, you can use `contains(where:)`:

let g = a.contains(where: { $0.caseInsensitiveCompare("B") == .orderedSame})
print(g) //->true

(facepalm) That's what I get for coding late on a Sunday night. Thank you.

Array&lt;T&gt;.first(where:) gives "cannot call value of non-function"
 
 
Q