Swift Combine: scan() method. The most useful operator

There’s another useful operator in the combine framework. It’s called scan(). Now let’s check out this useful operator.


import Combinelet publisher = (1...10).publisher// scan's 1st argument is the initial result
// closure's 1st argument is the nextResult
// closure's 2nd argument is the values
// closure's return type is the result
publisher.scan(0) { nextReuslt, value -> Int in
return nextReuslt + value // appending item to the array
.sink { value in
print(value) // 1,3,6,10,15,21,28,36,45,55

I created a sequence which goes from 1 to 10. You can simply call publisher.scan().


Take a look at the signature for the scan operator really carefully.

The first argument is initialResult, which can be of any type. So, this is up to you, whatever type that you want to provide.

The next argument is actually a closure that takes in the type of the first argument that you have set up and the second argument is the type of integer which you can see the value is currently integer.

So, If I go ahead and start using the scan type, it is going to return the type that I specified initially.

Finally, in sink() method, you get the steam of the partial result.


  • scan’s 1st argument is the initial result, you can specify datatype here.
  • scan’s 2nd argument is a closure that takes first argument of partial result and the second argument of value.
  • When receiving values, you receive the stream of partial results.



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!