Contents

~=(_:_:)

Returns a Boolean value indicating whether an argument matches nil.

Declaration

static func ~= (lhs: _OptionalNilComparisonType, rhs: borrowing Wrapped?) -> Bool

Parameters

  • lhs:

    A nil literal.

  • rhs:

    A value to match against nil.

Discussion

You can use the pattern-matching operator (~=) to test whether an optional instance is nil even when the wrapped value’s type does not conform to the Equatable protocol. The pattern-matching operator is used internally in case statements for pattern matching.

The following example declares the stream variable as an optional instance of a hypothetical DataStream type, and then uses a switch statement to determine whether the stream is nil or has a configured value. When evaluating the nil case of the switch statement, this operator is called behind the scenes.

var stream: DataStream? = nil
switch stream {
case nil:
    print("No data stream is configured.")
case let x?:
    print("The data stream has \(x.availableBytes) bytes available.")
}
// Prints "No data stream is configured."