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 guardguard let in Swift?guard letguard let is used to unwrap optionals safely in Swift.guard let forces an early exit from the current scope, keeping code clean.guard let = unwrap + early exit [OK]guard let to unwrap an optional name?guard let syntaxguard let constantName = optionalValue else { exit }.func greet(_ name: String?) {
guard let unwrappedName = name else {
print("No name provided")
return
}
print("Hello, \(unwrappedName)!")
}
greet(nil)
greet("Alice")guard let:func checkAge(_ age: Int?) {
guard let age = age {
print("Age is \(age)")
} else {
print("Age not provided")
}
}guard let, which code correctly implements this behavior?Pass the test and this pattern moves unknown