Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Swift Array, is there a function that returns the last index based in where clause?

Tags:

swift

The function index of an Swift array returns the first element based on the condition inside the where clause. Is there a way to get the last element with this condition?

For example, I want something like this (I know there is no function called lastIndex. This function or similar is what I'm searching for):

let array = [1, 2, 3, 4, 5, 3, 6]

let indexOfLastElementEquals3 = array.lastIndex(where: { $0 == 3 })

print(indexOfLastElementEquals3) //5 (Optional)
like image 426
Roberto Sampaio Avatar asked May 10 '18 19:05

Roberto Sampaio


People also ask

How do you get the last element of an array in Swift?

To get the last element of an array in Swift, access last property of this Array. Array. last returns the last element of this array. If the array is empty, then this property returns nil .

How do you get the index of an element in an array in Swift?

To find the index of a specific element in an Array in Swift, call firstIndex() method and pass the specific element for of parameter. Array. firstIndex(of: Element) returns the index of the first match of specified element in the array. If specified element is not present in the array, then this method returns nil .

What does .first do in Swift?

Returns the first element of the sequence that satisfies the given predicate.

What does array enumerated method does in Swift?

enumerated()Returns a sequence of pairs (n, x), where n represents a consecutive integer starting at zero and x represents an element of the sequence.


1 Answers

lastIndex(where:) and related methods were added in Swift 4.2, see

  • SE-0204 Add last(where:) and lastIndex(where:) Methods.

In earlier Swift versions you can use index(where:) on the reversed view of the collection:

let array = [1, 2, 3, 4, 5, 3, 6]

if let revIndex = array.reversed().index(where: { $0 % 2 != 0 } ) {
    let indexOfLastOddElement = array.index(before: revIndex.base)
    print(indexOfLastOddElement) // 5
}

Or as a single expression:

let indexOfLastOddElement =  array.reversed().index(where: { $0 % 2 != 0 } )
    .map { array.index(before: $0.base) }

print(indexOfLastOddElement) // Optional(5)

revIndex.base returns the position after the position of revIndex in the underlying collection, that's why we have to “subtract” one from the index.

For arrays this can be simplified to

    let indexOfLastOddElement = revIndex.base - 1

but for collections with non-integer indices (like String) the above index(before:) methods is needed.

like image 185
Martin R Avatar answered Oct 27 '22 14:10

Martin R