Pattern Match Operator

In Swift, it is possible to use the pattern match operator ~= to match an integer value with a range of integers. This can be also be used in if statements. Doing this range check could be helpful for testing if an index into an array is within range before trying to access an array element through subscript. Here is the overloaded type declaration for the range checking pattern match operator:

func ~=<I : ForwardIndexType where I : Comparable>(pattern: Range<I>, value: I) -> Bool

Here is an example of checking to see whether an index into an array is within range:

let arrayOfStrings = ["foo", "bar", "baz"]
let desiredIndex = 1

if 0..<arrayOfStrings.count ~= desiredIndex {
    print("Index \(desiredIndex) is within range")
    print(arrayOfStrings[desiredIndex])
} else {
    print("Index \(desiredIndex) is out of range")
    print(arrayOfStrings[desiredIndex]) // Will crash
}

// "Index 1 is within range"
// "bar"

Enumeration Case Pattern Expansion

Swift 2 expanded the enumeration case pattern beyond switch to also include if, while, guard, and for-in. So now the previous example could be rewritten to use the more readable if case:

if case 0..<arrayOfStrings.count = desiredIndex {
    print("Index \(desiredIndex) is within range")
    print(arrayOfStrings[desiredIndex])
} else {
    print("Index \(desiredIndex) is out of range")
    print(arrayOfStrings[desiredIndex]) // Will crash
}

// "Index 1 is within range"
// "bar"