In this article, we will master seven useful sequential Combine operators. We will use an Xcode Playground to quickly experiment with examples.

The source code of all the examples is available at the bottom of the article.


Let’s Start

These are the operators we are going to explore:

  • .first and .first(where:)
  • .last and .last(where:)
  • .output(at:) and .output(in:)
  • .count
  • .contains and .contains(where:)
  • .allSatisfy
  • .reduce

Without further ado, let’s begin working with them.


1. first

As its name suggests, the .first operator group allows us to obtain the first element of a sequence:

import Foundation
	import Combine

	var subscriptions = Set<AnyCancellable>()

	func firstExample() {
	    let intPublisher = [10, 20, 100, 200].publisher

	    intPublisher
	        .first()
	        .sink(receiveValue: { print("First: \($0)") })
	        .store(in: &subscriptions)
	}

The result is 10 printed out:

We also can specify a predicate using the .first(where) version of the operator:

func firstWhereExample() {
	    let intPublisher = [23, 33, 50, 27, 101, 108].publisher

	    intPublisher
	        .first(where: { $0.isMultiple(of: 2) })
	        .sink(receiveValue: { print($0) })
	        .store(in: &subscriptions)
	}

As you might have guessed, we have 50 printed in the console:


2. last

Just like we obtained the first element of a sequence, we can also get the last one:

func lastExample() {
	    let intPublisher = [10, 20, 100, 200].publisher

	    intPublisher
	        .last()
	        .sink(receiveValue: { print("Last: \($0)") })
	        .store(in: &subscriptions)
	}

Similarly, we can provide a condition:

func lastWhereExample() {
	    let intPublisher = [23, 33, 50, 27, 101, 108].publisher

	    intPublisher
	        .last(where: { $0.isMultiple(of: 2) })
	        .sink(receiveValue: { print($0) })
	        .store(in: &subscriptions)
	}

We see that 108 is printed, as it is the last element that satisfies the predicate:


3. output

The .output(at:) version of this operator obtains a certain element at the specified index:

func outputAtExample() {
	    let stringPublisher = ["A", "B", "C", "D"].publisher

	    stringPublisher
	        .output(at: 3)
	        .sink(receiveValue: { print("Output: \($0)") })
	        .store(in: &subscriptions)
	}

The index is 3. Therefore, “D” is printed out:

We can also obtain all the elements that belong to the specified range using the .output(in:) version:

#swift #xcode #mobile #ios #programming

7 Sequential Operators You Should Know From Swift Combine
7.85 GEEK