if let / guard let (Optional Binding)
Swift's if let and guard let are syntax for safely unwrapping Optionals. They extract the inner value as a constant or variable only when it is not nil, allowing you to handle it safely.
Syntax
// if let
if let constantName = optionalValue {
// constantName is available here (non-Optional)
}
// if var (mutable)
if var variableName = optionalValue {
variableName = newValue // can be modified
}
// Unwrap multiple Optionals at once
if let a = optA, let b = optB, a > 0 {
// runs only if both a and b are non-nil, and a is greater than 0
}
// Swift 5.7+: shorthand with the same name
if let name {
// unwraps name (Optional) and uses it under the same name
}
Syntax List
| Syntax | Description |
|---|---|
| if let constant = optional { } | Unwraps the value as a constant when it is not nil. |
| if var variable = optional { } | Unwraps the value as a mutable variable when it is not nil. |
| if let a = opt, let b = opt2 { } | Unwraps multiple Optionals at the same time. |
| if let constant = optional, condition { } | Combines unwrapping with an additional condition check (equivalent to where). |
| if let name { } | Shorthand that unwraps an Optional into a variable of the same name (Swift 5.7+). |
| guard let constant = optional else { return } | Returns early when the value is nil; the constant is available for the rest of the scope. |
Sample Code
// Basic if let
let input: String? = "42"
if let value = Int(input!) {
print("Conversion succeeded: \(value)")
} else {
print("Conversion failed")
}
// Unwrap multiple Optionals at once
let firstName: String? = "Taro"
let lastName: String? = "Yamada"
if let first = firstName, let last = lastName {
print("Full name: \(last) \(first)")
}
// Check a condition at the same time
let score: Int? = 85
if let s = score, s >= 60 {
print("Passed: \(s) points")
}
// Shorthand syntax (Swift 5.7+)
let name: String? = "Hanako"
if let name {
print("Hello, \(name)!") // use name directly
}
// Using guard let
func printLength(of str: String?) {
guard let str = str else {
print("No string provided")
return
}
print("Character count: \(str.count)")
}
printLength(of: "Hello")
printLength(of: nil)
Overview
Optional Binding (if let / guard let) is the most fundamental and safe way to work with Optionals in Swift. Once unwrapped, the constant or variable is treated as non-Optional within its scope.
When unwrapping multiple Optionals at once, if even one of them is nil, the else branch (or the guard else branch) is executed. An unwrapped constant is valid only within the corresponding if/guard block (with guard let, it is valid for the entire enclosing scope).
For the operator that returns a default value when nil, see ?? (Nil-Coalescing Operator).
If you find any errors or copyright issues, please contact us.