Swift Combine: output() operator

KD Knowledge Diet
1 min readFeb 10

--

Let’s go ahead and check out another sequence operator. This operator is called output(). output() operator comes in two different variations.

First variation of ‘output(at: Int)’ operator

let publisher = ["A", "B", "C", "D"].publisher 
publisher
.output(at: 1)
.sink {
print($0) // "B"
}

To show how output(at: Int) operator works, I created a publisher with array of strings.

output(at: Int) operator simply asks you which index you want to include. If you pass ‘1’, then index 1 will go to the downstream. As you can see, since I passed ‘1’, only ‘B’ is printed out.

Second variation of ‘output(at: Int)’ operator

let publisher = ["A", "B", "C", "D"].publisher 
publisher
.output(in: 0...2)
.sink {
print($0) // "A", "B", "C"
}

output(in: Range<Int>) takes in range to select multiple indexes. In this case, I passed ‘0...2’, so items from index 0 to 2 will be printed out.

Conclusion

  • output(at: Int) returns you the specific element of index you passed
  • output(in: Range<Int) returns you the elements within the range you defined.

--

--

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!