Swift Combine: collect() operators, very detailed explanation
collect() operator is the most basic form of combine operators. What it does is to take sequence of data and gives you an array.
collect() operator belongs to Transformation Operator.
The operator, as the name suggests, it’s going to collect different items and give you an array of items.
[1, 2, 3, 4]
}[1, 2, 3, 4]
.collect() // Your operator before sink()
print($0) // Output: [1,2,3,4]
collection() , you will receive a stream of integers in the code example above. But if you call
sink(), then you will receive the entire array of elements.
That’s the whole job of
collect() operator. It collects items and give you an array of items.
Specify some values
[1, 2, 3, 4]
print($0) // Output: [1,2], [3,4]
By giving arguments in
collection() method like
collect(2), you can specify the size of arrays and your arrays will be split.
This is really useful if you’re building some kind of application where you want to group or chunk items into different pieces and then most probably displays some sort of a grid control.
What happens if elements are not enough?
[1, 2, 3, 4, 5]
print($0) // Output: [1,2], [3,4], 
What will happen is that the last item will be the only item in a separate array.
collect()collects different items and give you an array of items.
- If you specify the size of an array by giving an argument
collect(2), you will get split arrays of size 2.
- If there are not enough elements, the last element returned won’t have the size of the arrays you specified.