We use the last(where:)
method to get the last element of an array that satisfies a given condition.
arr.last(where: condition)
arr
: This is the array for which we want to find the last element, in order to satisfy a given condition.
Condition:
This closure takes an array element as its argument and returns a Boolean
value, indicating whether the element matches the condition.
What is returned is the last element of the array that satisfies the condition. Otherwise, nothing is returned if there is no element that satisfies the condition.
let evenNumbers = [2, 4, 6, 8, 10]let twoLetterWords = ["up", "go", "me", "we"]let numbers = [2, 3, -4, 5, -9]// invoke the last(where:) methodlet lastGreaterThanFive = evenNumbers.last(where: {$0 >= 5})!let lastTwoLetters = twoLetterWords.last(where: {$0.count == 2})!let lastNegative = numbers.last(where: {$0 < 0})!// print resultsprint(lastGreaterThanFive)print(lastTwoLetters)print(lastNegative)
last(where:)
method on the arrays we created and store the returned results in some variables.