Expression pattern
With all the pattern matching skills you’ve developed so far, you’re finally ready to learn what’s underneath the hood. The expression pattern is simple, but oh, so powerful.
In the beginning of this chapter you saw the example tuple pattern (x, 0, 0). You learned that, internally, the tuple is a comma-separated list of patterns. You also learned that the x is an identifier pattern, while the 0’s are examples of the expression pattern. So the internal patterns of this tuple are (identifier, expression, expression).
The expression pattern compares values with the ~= pattern matching operator. The match succeeds when a comparison results in a true boolean value. If the values are of the same type, the common == equality operator will perform the comparison instead. You’ve already learned how to implement Equatable and == for your own named types back in Chapter 17, “Protocols”.
When the values aren’t of the same type or the type doesn’t implement the Equatable protocol, the ~= pattern matching operator will be used. For instance, the compiler uses the ~= operator to check whether an integer value falls within a range. The range is certainly not an integer, so the compiler cannot use the == operator. However, you can conceptualize the idea of checking whether an Int is within a range. That’s where the ~= pattern matching operator comes in:
let matched = (1...10 ~= 5) // true
As in the definition of a case condition, the pattern is required to be on the left- hand side of the operator, and the value on the right-hand side of the operator. Here’s what the equivalent case condition looks like:
if case 1...10 = 5 { print("In the range")
}
This if statement is functionally equivalent to using the ~= operator in the previous example.