Swift Combine: first(), last() operator

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

first()

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

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()

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

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.

--

--

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

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
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!