For an array:
var arr = [3,2,1,2,1,4,5,8,6,7,4,2]
I can find the first matching element
arr.first(where: {$0 == 2})!
But the last
arr.last(where: {$0 == 2})
Returns:
cannot call value of non-function type 'Int?'
Why?
For an array:
var arr = [3,2,1,2,1,4,5,8,6,7,4,2]
I can find the first matching element
arr.first(where: {$0 == 2})!
But the last
arr.last(where: {$0 == 2})
Returns:
cannot call value of non-function type 'Int?'
Why?
last(where:)
was added in Swift 4.2 (Xcode 10).
If you need to find the last match using Swift 4.1 or earlier, you can do:
let last = arr.reversed().first { $0 == 2 }
As already mentioned by rmaddy this method still in beta. If you would like to add this functionality also to Swift 4.1 you can extend BidirectionalCollection
as follow:
extension BidirectionalCollection {
func last(where predicate: (Element) throws -> Bool) rethrows -> Element? {
return try reversed().first(where: predicate)
}
}