Swift Combine: first(), last() operator

KD Knowledge Diet
2 min readFeb 5

--

Now let’s go ahead and take a look at first() and last() operators.

first()

let publisher = ["A", "B", "C", "D"].publisher publisher
.first()
.sink {
print($0) // "A"
}

To explain first() operator, I created an array which contains different elements and made it a publisher. When you use first() operator in the sequence, it will return you the first element of your collection. This is how first() operator works.

Adding condition with first() operator

let publisher = ["A", "B", "C", "D"].publisher publisher
.first(where: { "Cat".contains($0) })
.sink {
print($0) // "C"
}

When you provide a condition using first(where:), then the first element that satisfies your condition will go into the downstream. (.sink). In this example, element "C" satisfies the condition first, so you can see “C” is printed out.

last()

let publisher = ["A", "B", "C", "D"].publisher publisher
.last()
.sink {
print($0) // "A"
}

It’s very intuitive to understand when you know how first() operator. But in this case, last() operator will return you the last element of your collection. As you can see, the last element of the array is “D”, so you can check “D” is printed out.

Adding condition with last() operator

let publisher = ["A", "B", "C", "D"].publisher publisher
.last(where: { "Cat".contains($0) })
.sink {
print($0) // "C"
}

When you provide a condition using last(where:), then the last element that satisfies your condition will go into the downstream. (.sink). In this example, element "C" satisfies the condition last, so you can see “C” is printed out.

Conclusion

  • first() operator returns you the first element of the collection.
  • first(where:) operator returns you the first element of the collection that satisfies the condition you defined.
  • last() operator returns you the last element of the collection.
  • last(where:) operator returns you the last element of the collection that satisfies the condition you defined.

--

--

KD Knowledge Diet

Software Engineer, Mobile Developer living in Seoul. I hate people using difficult words. Why not using simple words? Keep It Simple Stupid!