Swift Combine: prefix(until:)
Let’s go ahead and take a look at some filter operators that are going to limit the value. What kind of values or what amount of values passes through. One of the first operators that you are going to look at is the prefix operator.
prefix()
let numbers = (1...10).publishernumbers
.prefix(2)
.sink {
print($0)
}
I created a range from 1 to 10 and made it a publisher. Now, the prefix naming is a little bit weird. Basically, it is saying that you go ahead and select two items, the first two items from this particular range. So, passing in two with prefix()
method means that the two initial values of that particular publisher.
So, this is a simple operator that simply selects the start of the sequence number of values.
prefix(while: ) and prefix(untilOutputFrom: )
let numbers = (1...10).publishernumbers.prefix(while: { $0 < 3 })
.sink {
print($0) // 1, 2
}
Now the prefix operator does come with different kinds of scenarios or different kind of overloaded methods. One of the methods is prefix(while:)
operator. It also has prefix(untilOutputFrom:)
.
Conclusion
- prefix(maxLength: ) allows you to select first items of the sequence.
- It also has prefix(while: ) and prefix(untilOutputFrom:).