An expression pattern represents the value of an expression and is evaluated by comparing that value against a control expression using the Swift standard library’s pattern matching operator (Documentation Index
Fetch the complete documentation index at: https://docs.syntblaze.com/llms.txt
Use this file to discover all available pages before exploring further.
~=). It acts as the underlying mechanism for evaluating case labels in switch statements, catch clauses, and if case / guard case constructs.
When the Swift compiler encounters an expression pattern, it implicitly translates the match attempt into a function call to the ~= operator.
The Pattern Matching Operator (~=)
The core of the expression pattern is the ~= operator. The compiler requires this operator to return a Bool indicating whether the pattern successfully matches the value.
The function signature for the operator strictly dictates the order of operands:
- Left-Hand Side (LHS): The pattern expression defined in the
case. - Right-Hand Side (RHS): The control value being evaluated.
Standard Library Implementations
Swift provides default overloads of the~= operator for common standard library types, defining their baseline expression pattern behavior:
EquatableTypes: If both the pattern and the value conform toEquatable, the~=operator delegates directly to the equality operator (==).
- Ranges: For types conforming to the
RangeExpressionprotocol (such asRangeandClosedRange), the~=operator evaluates whether the control value is contained within the bounds of the pattern’s range, utilizing thecontains(_:)method.
Operator Overloading for Custom Patterns
Because expression patterns are entirely dependent on the~= operator, the pattern matching system is extensible. Developers can define custom expression patterns by overloading the ~= operator for specific type combinations.
This is achieved by defining a static func for the ~= operator within a type (such as a struct, class, enum, or extension). Defining the operator as a static member prevents pollution of the global namespace while satisfying the compiler’s requirements. The function must accept the desired pattern type as the first parameter and the target value type as the second parameter.
case label does not need to match the type of the control value, provided a valid ~= overload exists to bridge them.
Master Swift with Deep Grasping Methodology!Learn More





