We can find the first element of an array that satisfies a given condition using the first(where:)
method.
array.first(where: condition)
array
: This is the array whose elements we want to search to find the first element that satisfies a given condition.
condition
: This is a closure that takes an array element as its argument and returns a Boolean value indicating whether there is an element that matches the condition.
. Here, n
is the length of the array. This element that needs to be searched can be the last one of the array in the worst case.
It is the first element of the array that satisfies the condition. Otherwise, null
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 first(where:) methodlet firstGreaterThanFive = evenNumbers.first(where: {$0 >= 5})!let firstTwoLetters = twoLetterWords.first(where: {$0.count == 2})!let firstNegative = numbers.first(where: {$0 < 0})!// print resultsprint(firstGreaterThanFive)print(firstTwoLetters)print(firstNegative)
first(where:)
method on the arrays we created and store the returned results in some variables.