TheDocumentation Index
Fetch the complete documentation index at: https://docs.syntblaze.com/llms.txt
Use this file to discover all available pages before exploring further.
~= (pattern matching) operator evaluates whether a specific value conforms to a defined pattern. It serves as the underlying boolean evaluation mechanism for Swift’s pattern-matching constructs, implicitly driving the execution of switch statement case labels, catch clauses, if case, guard case, for case, and while case statements.
Syntax and Operand Order
Unlike standard equality operators, the~= operator is asymmetrical. The order of operands is strictly defined and critical to its operation:
- Left-Hand Side (LHS): The pattern to match against.
- Right-Hand Side (RHS): The value being evaluated.
switch statement, it translates the case comparisons into ~= expressions. For example, a case 1...5: evaluating a bound value of 3 is compiled under the hood as 1...5 ~= 3.
Standard Library Behavior
The Swift Standard Library provides default overloads for the~= operator across several common protocols and types:
EquatableTypes: If the pattern and the value are of the same type and conform toEquatable,~=delegates directly to the==operator.- Ranges (
Range,ClosedRange): When the pattern is a range and the value is of the range’s underlyingBoundtype,~=evaluates topattern.contains(value). - Optionals: Evaluates whether the unwrapped value of an optional matches the pattern. If the pattern itself is
nil(e.g.,case nil:), the operator evaluates totruewhen the value isnil. If the pattern is non-nilbut the evaluated value isnil, it safely evaluates tofalse. - Errors: Matches specific error types or domains within
catchblocks.
Custom Overloading
The~= operator can be globally overloaded to define custom pattern-matching logic, often between disparate types. To implement custom pattern matching, define a function for the ~= operator that accepts the concrete pattern type as the first parameter and the concrete value type as the second parameter, returning a Bool.
Warning: Never use unconstrained generic parameters (e.g., <T, U>) when overloading ~=. Doing so creates a global catch-all that disables compile-time type checking for pattern matching across the entire module, allowing fundamentally incompatible types to compile in switch statements while silently failing at runtime.
PrefixPattern is used as a case label against a TextValue.
Master Swift with Deep Grasping Methodology!Learn More





