merge vs zip

Combine Mid-level Swift 5.1+ iOS 13+ Reviewed By Alok Singh

Predict the output

What does this print?

let a = PassthroughSubject<Int, Never>()
let b = PassthroughSubject<String, Never>()
a.zip(b)
    .sink { print($0, $1) }
    .store(in: &cancellables)
a.send(1)
a.send(2)
b.send("x")
b.send("y")
Options
Hint 1 of 1

Pair the first with the first.

Choose an answer, then open Show answer below to check it.

Show answer

Answer: B 1 x, 2 y

Correct. zip pairs values by position.

Why not the others?
  • A 2 x, 2 y. That is combineLatest-style behaviour.
  • C 1 x. The second pair is complete once y arrives.
  • D 1, 2, x, y. That is merge, which needs matching types.

30-second answer

merge interleaves values from publishers of the same type into one stream as they arrive. zip pairs values by position: the first of each, then the second of each, so it waits for every upstream to emit before producing a tuple. Use merge for 'any of these events'; use zip to wait for matching results, such as two parallel requests.

Practise saying it · 30 s. No recording, just a timer

Compare merge and zip.

Say your answer out loud, then check which of these points you covered:

  • merge interleaves
  • zip pairs by position
  • async let for one-shot pairs

Deep dive

merge requires the same Output and Failure types.

zip buffers values from the faster publisher.

zip finishes when any upstream finishes and has no unmatched values.

For two one-shot async calls, async let is now clearer than zip.

Common mistakes

  • Using zip for UI state, which stalls when one input stops emitting.
  • Using merge for different value types.

Senior take & follow-ups

Seniors map each operator to a timeline and pick async let for one-shot pairs.

Follow-up questions

Think of your answer first, then open the hint.

  1. What does zip do with an extra value from one side?

    Show hint

    Buffers it until the other side emits.

  2. What replaces zip for two parallel requests?

    Show hint

    async let.

Suggest a fix if something here is wrong or out of date.