Operator: ~=

operator ~= { associativity precedence }

Declarations

func ~= <T>(_: T, b: T)

Returns a Boolean value indicating whether two arguments match by value equality.

The pattern-matching operator (~=) is used internally in case statements for pattern matching. When you match against an Equatable value in a case statement, this operator is called behind the scenes.

let weekday = 3
let lunch: String
switch weekday {
case 3:
    lunch = "Taco Tuesday!"
default:
    lunch = "Pizza again."
}
// lunch == "Taco Tuesday!"

In this example, the case 3 expression uses this pattern-matching operator to test whether weekday is equal to the value 3.

Note: In most cases, you should use the equal-to operator (==) to test whether two instances are equal. The pattern-matching operator is primarily intended to enable case statement pattern matching.

Parameters: lhs: A value to compare. rhs: Another value to compare.

Declaration

func ~=<T>(a: T, b: T) -> Bool where T : Equatable
func ~=(_: _OptionalNilComparisonType, rhs: Wrapped?)

Returns a Boolean value indicating whether an argument matches nil.

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."

Note: To test whether an instance is nil in an if statement, use the equal-to operator (==) instead of the pattern-matching operator. The pattern-matching operator is primarily intended to enable case statement pattern matching.

Parameters: lhs: A nil literal. rhs: A value to match against nil.

Declaration

func ~=(lhs: _OptionalNilComparisonType, rhs: Wrapped?) -> Bool
func ~=(_: Self, value: Self.Bound)

Declaration

func ~=(pattern: Self, value: Self.Bound) -> Bool

Declared In

RangeExpression
func ~=(_: Self, value: Self.Bound)

Declaration

func ~=(pattern: Self, value: Self.Bound) -> Bool

Declared In

RangeExpression
func ~=(_: Self, value: Self.Bound)

Declaration

func ~=(pattern: Self, value: Self.Bound) -> Bool

Declared In

RangeExpression
func ~=(_: Self, value: Self.Bound)

Declaration

func ~=(pattern: Self, value: Self.Bound) -> Bool

Declared In

RangeExpression
func ~=(_: Self, value: Self.Bound)

Declaration

func ~=(pattern: Self, value: Self.Bound) -> Bool

Declared In

RangeExpression