Swift Combine: prepend() operator
In this tutorial, you are going to look at prepend()
operator. Just as the name implies, the prepend() operator is going to append element in your sequence.
A publisher
let numbers = (1...5).publisher
numbers.sink {
print($0) // 1,2,3,4,5
}
I created a range from 1 to 5 and made it a publisher. You can see 1,2,3,4,5 are printed out. But what if I want to prepend a value before the sequence happens?
prepend()
let numbers = (1...5).publisher
numbers
.prepend(100)
.sink {
print($0) // 100, 1,2,3,4,5
}numbers
.prepend(100, 101)
.sink {
print($0) // 100, 101, 1,2,3,4,5
}numbers
.prepend(100, 101)
.prepend(-1, -2)
.sink {
print($0) // -1, -2, 100, 101, 1,2,3,4,5
}numbers
.prepend([45, 47])
.sink {
print($0) // 45, 47, 1, 2, 3, 4, 5
}
When you use this .prepend()
operator, you can prepend some element. You can actually pass in a number or numbers to prepend.
Since you are using combination operators and the reactive way of writing your code, you can also chain different operator.
Not only you can provide a variadic parameter (sending multiple values in the argument), you can pass in an array.
Combining Publisher with prepend()
let numbers = (1...5).publisher
let publisher2 = (500...510).publishernumbers
.prened(publisher2)
.sink {
print($0) //500, 501, 502, 503, 504, 505, ... 510, 1, 2, 3, 4, 5
}
Besides numbers, I created another publisher from 500 to 510. You can pass in a publisher. You can check the result.
Conclusion
prepend()
allows you to add elements before the sequence.- You can pass in
variadic parameters
,arrays
andpublisher
as a parameter.