Skip to main content
guard let is a control flow construct used for optional binding that unwraps an optional value and binds it to a new constant or variable, enforcing an early exit if the optional evaluates to nil. Crucially, unlike if let bindings where the unwrapped value is restricted to the local scope of the conditional block, a variable bound by guard let is injected into the scope immediately enclosing the guard statement. Syntax
Execution Mechanics
  1. Evaluation: The optional expression is evaluated.
  2. Failure (nil): If the expression is nil, the else block executes. The Swift compiler mandates that the else block must terminate the current scope. This requires a control transfer statement such as return, throw, break, continue, or a call to a function that returns Never (e.g., fatalError()).
  3. Success (Non-nil): If the expression contains a value, it is safely unwrapped and assigned to the bound identifier. Execution skips the else block and proceeds to the subsequent lines.
Scope and Shadowing The primary mechanical distinction of guard let is scope inversion. The bound identifier remains in memory and is accessible for the remainder of the enclosing block (e.g., the rest of the function or loop). It is standard practice in Swift to use variable shadowing with guard let, assigning the unwrapped value to a constant with the exact same name as the original optional variable. As of Swift 5.7, this is accomplished using a shorthand syntax that omits the explicit right-hand assignment:
For codebases supporting Swift versions prior to 5.7, the explicit assignment syntax is required to achieve the same shadowing behavior:
Compound Statements Multiple optional bindings and Boolean conditions can be evaluated in a single guard statement by separating them with commas. Evaluation proceeds sequentially from left to right. If any binding evaluates to nil or any Boolean condition evaluates to false, evaluation halts immediately (short-circuiting) and the else block executes.
Mutability While guard let binds the unwrapped value to an immutable constant, you can use guard var to bind the unwrapped value to a mutable variable. This mutable variable is local to the enclosing scope, and modifying it does not mutate the original optional.
Tired of Poor Swift Skills? Fix That With Deep Grasping!Learn More