Reactive Programming in iOS with Combine

Feb 4 2021 Swift 5.3, macOS 11.0, Xcode 12.2

Part 2: Transforming & Filtering Operators

7. Transforming Operators

Lesson Complete

Play Next Lesson
Next
Save for later
About this episode

See course reviews

See forum comments
Cinema mode Mark as Complete Download course materials
Previous episode: 6. Introduction Next episode: 8. More Transforming Operators

This video was last updated on Feb 4 2021

Heads up... You've reached locked video content where the transcript will be shown as obfuscated text.

You can unlock the rest of this video course, and our entire catalogue of books and videos, with a kodeco.com Professional subscription.

The first type of operators we’ll focus on are Transforming operators. This style of operator is the most common, and is used to manipulate values coming from publishers into a format that is suitable for subscribers downstream. As we discuss this type of operator, you’ll see many similarities (and differences!) with operators from the Swift standard library such as map and flatMap.

example(of: "collect") {
  ["A", "B", "C", "D", "E"].publisher
    .sink(receiveCompletion: { print($0) },
          receiveValue: { print($0) })
    .store(in: &subscriptions)
}
["A", "B", "C", "D", "E"].publisher
  .collect()
  .sink(receiveCompletion: { print($0) },
        receiveValue: { print($0) })
  .store(in: &subscriptions)
example(of: "map") {
  // 1
  let formatter = NumberFormatter()
  formatter.numberStyle = .spellOut

  // 2
  [123, 4, 56].publisher
    // 3
    .map {
      formatter.string(for: NSNumber(integerLiteral: $0)) ?? ""
    }
    .sink(receiveValue: { print($0) })
    .store(in: &subscriptions)
}
example(of: "replaceNil") {
  // 1
  ["A", nil, "C"].publisher
    .replaceNil(with: "-") // 2
    .sink(receiveValue: { print($0) }) // 3
    .store(in: &subscriptions)
}
example(of: "replaceNil") {
  ["A", nil, "C"].publisher
    .replaceNil(with: "-")
    .map { $0! }
    .sink(receiveValue: { print($0) })
    .store(in: &subscriptions)
}
example(of: "replaceEmpty(with:1)") {
  // 1
  let empty = Empty<Int, Never>()
  // 2
  empty
    .replaceEmpty(with: 1)
    .sink(receiveCompletion: { print($0) },
          receiveValue: { print($0) })
    .store(in: &subscriptions)
}