Skip to main content

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.

A value-binding pattern binds matched values to new variable or constant names within the scope of a control flow statement. It extracts a value from a compound type—such as an enumeration’s associated value, a tuple, or an optional—and assigns it to a local identifier using the let or var keywords.

Syntax Structure

The pattern is initiated by prefixing an identifier or a compound pattern with a mutability keyword.
case let <identifier>:
case var <identifier>:
When a match succeeds, the bound identifier becomes available as a local shadow copy within the execution block of the matching statement (e.g., a switch case block).

Mutability and Scope

  • let Binding: Creates an immutable constant. The bound value cannot be modified within the matched scope.
  • var Binding: Creates a mutable variable. Modifications made to this variable are local to the matched scope and do not mutate the original underlying data structure.

Tuple Distribution

When applying a value-binding pattern to a tuple, Swift allows the mutability keyword to be distributed across all elements of the tuple. Placing let or var outside the tuple parentheses implicitly applies that binding to every identifier within the tuple.
// Distributed binding (applies 'let' to both x and y)
case let (x, y):

// Equivalent inline binding
case (let x, let y):

// Mixed mutability (requires inline binding)
case (let x, var y):

Enumeration Associated Values

Value-binding patterns are the primary mechanism for extracting associated values from enumerations. The binding can occur either inside the associated value parentheses or outside the enumeration case entirely.
// Binding applied to specific associated values
case .identifier(let value1, var value2):

// Distributed binding applied to the entire case
case let .identifier(value1, value2):

Optional Pattern Integration

The value-binding pattern frequently combines with the optional pattern (?) to unwrap and bind the underlying value of an Optional<Wrapped> type in a single operation.
// Binds the unwrapped value if the optional is not nil
case let unwrappedValue?:

Pattern Composition and where Clauses

Value-binding patterns can be constrained using where clauses. The bound identifiers are evaluated in the where expression before the pattern match is considered successful. If the where clause evaluates to false, the binding is discarded, and pattern matching continues to the next branch.
case let (x, y) where x == y:
Master Swift with Deep Grasping Methodology!Learn More