Skip to main content
A tuple pattern is a comma-separated list of zero or more patterns enclosed in parentheses, used to match and destructure the corresponding elements of a tuple value. It evaluates to true if, and only if, every sub-pattern within the parentheses successfully matches the corresponding element in the target tuple.

Syntax

Mechanics and Behavior

Arity and Type Matching The arity (number of elements) of the tuple pattern must exactly match the arity of the tuple being evaluated. The compiler enforces this strictly. Furthermore, the type of each sub-pattern must align with or be castable to the type of the corresponding tuple element.
Sub-Pattern Composition A tuple pattern is a composite pattern. Its elements can be any valid Swift pattern, allowing for complex matching logic within a single structure. Common sub-patterns include:
  • Expression Patterns: Matching exact literal values or expressions.
  • Wildcard Patterns (_): Explicitly ignoring specific elements at a given index without binding them to memory.
  • Value-Binding Patterns (let / var): Extracting elements into the local scope.
Type-Casting Patterns Tuple patterns support explicit type-casting patterns (is or as) to constrain matches dynamically. These type-casting patterns can be applied to individual elements within the tuple pattern, or to the entire tuple structure as a whole.
Nested Tuple Patterns Because tuple patterns accept any valid pattern as an element, they can be nested recursively to match multi-dimensional or hierarchical tuple structures. The compiler evaluates nested patterns depth-first.
Single-Element Tuples In Swift, a tuple with a single element is syntactically equivalent to the element itself. Therefore, a tuple pattern containing exactly one pattern is functionally identical to that single pattern without the enclosing parentheses.
Tired of Poor Swift Skills? Fix That With Deep Grasping!Learn More