Swift Combine: last() operator. Unknown but useful operator.
Let’s learn about the last()
operator. You can pretty much guess the last operator is going to find the the last value in the sequence that satisfies a particular condition that is set by you.
find the last element using last()
let numbers = (1...9).publisher
numbers
.last(where: { $0 % 2 == 0 })
.sink {
print($0) // 8
}
I created numbers with range from 1 to 9 and made it a publisher. You can clearly see that last()
operator takes a closure where you must define your condition. Here in this example, I wanted to find the last even number in the sequence.
This is the whole purpose of last()
operator. It is going to wait until the last value has been checked and then simply return the value which satisfies your condition.
Conclusion
last()
operator searches for the entire sequence to find the last element that meets your criteria.