SwiftMidMCQ
What is `guard let` vs `if let`?
Test your knowledge:
Explanation & Code
Answer: Both safely unwrap optionals, but they differ in scope and intent.
if let— unwrapped value exists only inside theifblockguard let— unwrapped value exists in the surrounding scope after the check; must exit early if condition fails
Code Example:
// if let — value scoped inside the block
if let username = getUsername() {
print("Welcome, \(username)")
}
// username not accessible here
// guard let — value available after the guard
func greetUser() {
guard let username = getUsername() else {
print("No user")
return // must exit
}
// username accessible here for the rest of the function
print("Welcome, \(username)")
}
Rule of thumb: Use guard let for preconditions at the top of a function. Use if let when the unwrapped value is only needed in one branch.
Rate your understanding: