Guard Let
Part of the Fundamentals section of Coddy's Swift journey — lesson 13 of 86.
While if let unwraps an optional and runs code when a value exists, guard let takes the opposite approach — it exits early when a value is missing. This is especially useful inside functions where you want to handle the "bad" case first and keep the main logic clean.
func greet(name: String?) {
guard let unwrappedName = name else {
print("No name provided")
return
}
print("Hello, \(unwrappedName)!")
}
greet(name: "Taylor") // Hello, Taylor!
greet(name: nil) // No name providedThe guard let statement checks if name has a value. If it doesn't, the else block runs and the function exits with return. If the optional contains a value, it's unwrapped into unwrappedName — and here's the key difference from if let: the unwrapped variable remains available for the rest of the function, not just inside a block.
This "early exit" pattern keeps your code readable by handling error cases upfront, so the main logic isn't nested inside multiple if statements.
Challenge
EasyWrite a function validateAge that takes an optional age parameter and uses guard let to safely unwrap it.
If the age is nil, return "Invalid age". Otherwise, return "Age: [value]" where [value] is the unwrapped age.
Parameters:
age(Int?): An optional integer representing a person's age
Returns: A string — either "Invalid age" if the input is nil, or "Age: [value]" with the unwrapped value.
Example: If age is 25, return "Age: 25". If age is nil, return "Invalid age".
Cheat sheet
Use guard let to unwrap an optional and exit early when a value is missing:
func greet(name: String?) {
guard let unwrappedName = name else {
print("No name provided")
return
}
print("Hello, \(unwrappedName)!")
}The guard let statement checks if the optional has a value. If it doesn't, the else block runs and exits the function with return. If the optional contains a value, it's unwrapped and remains available for the rest of the function scope.
This "early exit" pattern handles error cases upfront, keeping the main logic clean and unindented.
Try it yourself
func validateAge(age: Int) -> String {
// Write code here
}
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Fundamentals
4Operators Part 1
Arithmetic OperatorsModulo OperatorCompound AssignmentRecap - Simple MathComparison Operators7Basic IO
Print FunctionString InterpolationReadLine InputType ConversionRecap - Till 120Recap - True or False10Functions
Declare A FunctionParameters And ArgumentsReturn ValuesArgument LabelsRecap - Sigma FunctionRecap - Validation FunctionDefault Values13Iterating Over Sequences
Iterating Over ElementsThe Enumerated MethodIterating Over Strings P1Iterating Over Strings P22Variables
Let vs VarType AnnotationsNumbersStringBooleanNaming ConventionsRecap - Initialize Variables5Operators Part 2
Logical Operators Part 1Logical Operators Part 2Recap - Simple LogicLogical Operators Part 3Ternary Operator8Bill Split Calculator
Welcome MessageGetting Input3Optionals
What Are OptionalsUnwrapping With If LetGuard LetNil Coalescing OperatorRecap - Safe Unwrapping9Loops
For-In LoopWhile LoopRepeat-While LoopBreakContinueRecap - FactorialRanges In LoopsNested LoopRecap - Dynamic Input