Contents

contains(_:)

Publishes a Boolean value upon receiving an element equal to the argument.

Declaration

func contains(_ output: Self.Output) -> Publishers.Contains<Self>

Parameters

  • output:

    An element to match against.

Return Value

A publisher that emits the Boolean value true when the upstream publisher emits a matching value.

Discussion

Use contains(_:) to find the first element in an upstream that’s equal to the supplied argument. The contains publisher consumes all received elements until the upstream publisher produces a matching element. Upon finding the first match, it emits true and finishes normally. If the upstream finishes normally without producing a matching element, this publisher emits false and finishes.

In the example below, the contains(_:) operator emits true the first time it receives the value 5 from the numbers.publisher, and then finishes normally.

let numbers = [-1, 5, 10, 5]
numbers.publisher
    .contains(5)
    .sink { print("\($0)") }

// Prints: "true"

See Also

Applying matching criteria to elements