Swift Combine: first() operator, return only a single value!

KD Knowledge Diet
1 min readApr 29, 2022

--

first() operator is mainly used for finding different values. As the name suggests, it’s going to find the first element in a sequence which matches the condition you defined. As soon as it finds that particular ‘true’ value, it’s going to stop for searching for the sequence.

Find a single value

let numbers = (1...9).publishernumbers
.first(where: { $0 % 2 == 0 }) // what you are looking for
.sink {
print($0) //2, nothing more will be printed than 2
}

I created a number sequence which is going from 1 to 9 and made it a publisher. first()

operator takes a closure where you should define a certain condition.

Note that it only returns a single value which met your condition.

You can think first() operator as a kind of lazy operator. When it finds the first condition that meets the criteria, then it simply bails out at that moment and give you that particular number from the sequence. So this is the usage of first() operator in the combine framework.

Conclusion

  • first() operator only returns a single value which meets your criteria.

--

--

KD Knowledge Diet
KD Knowledge Diet

Written by 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!

No responses yet