Concept Flow - Guard let for early exit
Start Function
Evaluate guard let
Continue
Rest of [Return
End
The guard let checks if a value exists; if not, it exits early, otherwise continues with the unwrapped value.
func greet(name: String?) { guard let unwrappedName = name else { print("No name provided.") return } print("Hello, \(unwrappedName)!") }
| Step | Action | Condition | Result | Branch Taken | Output |
|---|---|---|---|---|---|
| 1 | Call greet(name: nil) | name != nil? | false | Early Exit | No name provided. |
| 2 | Return from function | - | - | - | - |
| 3 | Call greet(name: "Alice") | name != nil? | true | Continue | - |
| 4 | Unwrap name to unwrappedName | - | unwrappedName = "Alice" | Continue | - |
| 5 | Print greeting | - | - | - | Hello, Alice! |
| 6 | End function | - | - | - | - |
| Variable | Start | After Step 3 | After Step 4 | Final |
|---|---|---|---|---|
| name | nil or "Alice" | nil or "Alice" | nil or "Alice" | nil or "Alice" |
| unwrappedName | nil | nil | "Alice" | "Alice" |
guard let syntax:
guard let variable = optional else {
// early exit code
return
}
- Checks if optional has value
- If nil, runs else block and exits early
- If not nil, unwraps and continues
- Ensures safe use of unwrapped variable after guard