Operator

~=(_:_:)

Returns a Boolean value indicating whether a value is included in a range.

Declaration

static func ~= (pattern: Range<Bound>, value: Bound) -> Bool

Parameters

lhs

A range.

rhs

A value to match against lhs.

Discussion

You can use this pattern matching operator (~=) to test whether a value is included in a range. The following example uses the ~= operator to test whether an integer is included in a range of single-digit numbers.

let chosenNumber = 3
if 0..<10 ~= chosenNumber {
    print("\(chosenNumber) is a single digit.")
}
// Prints "3 is a single digit."

The ~= operator is used internally in case statements for pattern matching. When you match against a range in a case statement, this operator is called behind the scenes.

switch chosenNumber {
case 0..<10:
    print("\(chosenNumber) is a single digit.")
case Int.min..<0:
    print("\(chosenNumber) is negative.")
default:
    print("\(chosenNumber) is positive.")
}
// Prints "3 is a single digit."

See Also

Checking for Containment

func contains(Bound) -> Bool

Returns a Boolean value indicating whether the given element is contained within the range.

func contains(where: (Bound) -> Bool) -> Bool

Returns a Boolean value indicating whether the sequence contains an element that satisfies the given predicate.

func allSatisfy((Bound) -> Bool) -> Bool

Returns a Boolean value indicating whether every element of a sequence satisfies a given predicate.