guard let Unwrapping
guard let checks that a value exists, and if it doesn't, the function leaves right away instead of trying to continue without it.
In this page:
Basic guard let
guard let unwraps an optional and, if it fails, executes the else block which must leave the current scope, commonly via return.
Example: Basic guard let
func printUppercased(_ text: String?) {
guard let text = text else {
print("No text provided")
return
}
print(text.uppercased())
}
printUppercased("hello")
printUppercased(nil)
Login to try C/C++/Java/PHP code in the editor
Chaining Multiple guard let Unwraps
Multiple optionals can be unwrapped in a single guard let, all separated by commas, keeping validation logic compact at the top of a function.
Example: Chaining Multiple guard let Unwraps
func describe(name: String?, age: Int?) {
guard let name = name, let age = age else {
print("Missing information")
return
}
print("\(name) is \(age) years old")
}
describe(name: "Kim", age: 28)
describe(name: nil, age: 28)
Login to try C/C++/Java/PHP code in the editor
Common Mistakes
- Forgetting that
guard let'selsebranch must exit the current scope, just like a plainguard. - Using
guard letfor a value only needed briefly inside a small block, whereif letwould keep the scope tighter. - Not taking advantage of
guard let's biggest benefit -- the unwrapped constant stays available for the rest of the function, avoiding nested indentation.
Chapter Summary
guard let value = optional else { return }unwraps or exits the current scope.- This keeps the "happy path" code unindented and easy to read.
- The unwrapped constant remains usable for the rest of the enclosing function.
guard letis preferred overif letwhen a missing value should stop execution early.
🔒
Chapter Quiz — Complete all 8 topics to unlock
0/8 topics done
Complete these topics first: