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.

Obviously, collect() operator belongs to Transformation Operator.

What does collect() does?

The operator, as the name suggests, it’s going to collect different items and give you an array of items.

Usage

[1, 2, 3, 4]
.publisher
.sink {
print($0)
// Output
// 1
// 2
// 3
// 4
}
[1, 2, 3, 4]
.publisher
.collect() // Your operator before sink()
.sink {
print($0) // Output: [1,2,3,4]
}

Without using collection() , you will receive a stream of integers in the code example above. But if you call collect() before 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]
.publisher
.collect(2)
.sink {
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]
.publisher
.collect(2)
.sink {
print($0) // Output: [1,2], [3,4], [5]
}

What will happen is that the last item will be the only item in a separate array.

Conclusion

  • 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.

--

--

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!