0

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?

rmaddy
  • 314,917
  • 42
  • 532
  • 579
stevenpcurtis
  • 1,907
  • 3
  • 21
  • 47

2 Answers2

2

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 }
rmaddy
  • 314,917
  • 42
  • 532
  • 579
  • 3
    And for those worried about the performance of this: worry not, `reversed()` simply makes a wrapper around the source array, and just does some index math (`count - 1 - i`) to access an index `i`. There's no array copying going on. – Alexander Sep 03 '18 at 01:06
  • @Alexander TIL! Cool. – Oscar Apeland Sep 03 '18 at 12:19
1

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)
    }
}
Leo Dabus
  • 229,809
  • 59
  • 489
  • 571