What is the purpose of the guard statement in Swift?
The guard statement checks a condition and exits the current scope early if the condition is not met. It helps keep the main code path clear and avoids deep nesting.
Click to reveal answer
beginner
How does the guard statement improve code readability?
By handling error or invalid cases early and exiting, guard keeps the main logic at the top level without extra indentation, making the code easier to read and understand.
Click to reveal answer
intermediate
What must happen inside the else block of a guard statement?
The else block must exit the current scope using return, break, continue, or throw. This ensures the program does not continue if the condition fails.
Click to reveal answer
beginner
Example: What will this code print?<br><pre>func checkAge(_ age: Int?) {
guard let age = age, age >= 18 else {
print("Not allowed")
return
}
print("Allowed")
}
checkAge(20)
checkAge(15)
checkAge(nil)</pre>
The code prints: Allowed for 20 because age is valid and >= 18. Not allowed for 15 because age is less than 18. Not allowed for nil because age is missing.
Click to reveal answer
intermediate
Why is guard preferred over nested if statements for early exit?
guard reduces nested code blocks by exiting early when conditions fail. This leads to cleaner, flatter code that is easier to follow and maintain.
Click to reveal answer
What must the else block of a guard statement do?
AExit the current scope with return, break, continue, or throw
BDo nothing and continue execution
COnly print an error message
DDeclare new variables
✗ Incorrect
The else block must exit the current scope to prevent continuing when the guard condition fails.
Which keyword is used in Swift to check a condition and exit early if it fails?
Aguard
Bif
Cswitch
Dwhile
✗ Incorrect
guard is designed for early exit when a condition is not met.
What happens if the guard condition is true?
AThe code inside <code>else</code> runs
BThe program exits immediately
CExecution continues after the guard statement
DThe program crashes
✗ Incorrect
If the guard condition is true, the program continues normally after the guard statement.
Why is guard useful for unwrapping optionals?
AIt forces the optional to be nil
BIt unwraps the optional and exits early if nil
CIt converts optionals to strings
DIt ignores optionals
✗ Incorrect
guard let unwraps optionals and exits early if the value is nil, avoiding crashes.
Which of these is NOT a valid way to exit inside a guard else block?
Areturn
Bbreak
Ccontinue
Dprint("Error")
✗ Incorrect
Simply printing an error does not exit the scope; you must use return, break, continue, or throw.
Explain how the guard statement helps with early exit in Swift functions.
Think about how guard checks conditions and what happens if they fail.
You got /4 concepts.
Describe a real-life example where using guard for early exit makes code easier to read.
Imagine checking if a user input is valid before continuing.
You got /4 concepts.
Practice
(1/5)
1. What is the main purpose of using guard statements in Swift?
easy
A. To define functions with multiple parameters
B. To create loops that run a fixed number of times
C. To check a condition and exit early if it is false
D. To declare constants and variables
Solution
Step 1: Understand the role of guard
guard is used to check a condition and exit the current scope early if the condition is false.
Step 2: Compare with other options
Options A, B, and C describe functions, loops, and variable declarations, which are unrelated to guard.
Final Answer:
To check a condition and exit early if it is false -> Option C
Quick Check:
Guard = early exit on false condition [OK]
Hint: Guard exits early if condition fails, keeping code clean [OK]
Common Mistakes:
Confusing guard with if statements
Thinking guard creates loops
Using guard to declare variables
2. Which of the following is the correct syntax for a guard statement in Swift?
easy
A. guard condition { return }
B. guard (condition) { return }
C. guard else condition { return }
D. guard condition else { return }
Solution
Step 1: Recall the syntax of guard
The correct syntax is guard condition else { ... } where the else block handles the early exit.
Step 2: Check each option
guard condition else { return } matches the correct syntax. Options A, B, and D have missing else, extra parentheses, or misplaced keywords.
3. What will be the output of the following Swift code?
func checkAge(_ age: Int?) {
guard let age = age, age >= 18 else {
print("Access denied")
return
}
print("Access granted")
}
checkAge(nil)
checkAge(16)
checkAge(21)
medium
A. Access denied
Access denied
Access granted
B. Access granted
Access granted
Access granted
C. Access denied
Access granted
Access denied
D. Access granted
Access denied
Access denied
Solution
Step 1: Analyze the guard condition
The guard checks if age is not nil and at least 18. If false, it prints "Access denied" and returns early.
Step 2: Evaluate each function call
For checkAge(nil), age is nil -> prints "Access denied". For checkAge(16), age is 16 < 18 -> prints "Access denied". For checkAge(21), age is 21 ≥ 18 -> prints "Access granted".
Final Answer:
Access denied
Access denied
Access granted -> Option A
Quick Check:
Guard filters nil or under 18 = Access denied [OK]
Hint: Guard lets only valid age (18+) pass, else denies [OK]
Common Mistakes:
Ignoring nil check in guard
Assuming all calls print Access granted
Confusing guard with if
4. Identify the error in this Swift code using guard:
func greet(name: String?) {
guard name != nil else {
print("No name provided")
}
print("Hello, \(name!)")
}
medium
A. Incorrect use of optional binding in guard
B. Missing return or exit after guard else block
C. Using force unwrap (!) inside print
D. Guard condition should be inside parentheses
Solution
Step 1: Understand guard requirements
The else block of a guard must exit the current scope (return, break, continue, or throw).
Step 2: Check the code
The else block prints a message but does not return or exit, so the function continues and force unwraps a nil value, causing a runtime error.
Final Answer:
Missing return or exit after guard else block -> Option B
5. You want to write a function that takes an optional string and prints its uppercase version only if the string is non-empty. Using guard, which code snippet correctly implements this behavior?
hard
A. func printUpper(_ text: String?) {
guard let text = text, !text.isEmpty else {
print("Empty or nil string")
return
}
print(text.uppercased())
}
B. func printUpper(_ text: String?) {
if let text = text, !text.isEmpty {
print(text.uppercased())
} else {
print("Empty or nil string")
}
}
C. func printUpper(_ text: String?) {
guard text != nil else {
print("Empty or nil string")
return
}
print(text!.uppercased())
}
D. func printUpper(_ text: String?) {
guard let text = text else {
print("Empty or nil string")
return
}
if text.isEmpty {
print("Empty or nil string")
}
print(text.uppercased())
}
Solution
Step 1: Understand the requirements
The function must print uppercase only if the string is non-nil and not empty, else print a message and exit early.
Step 2: Evaluate each option
func printUpper(_ text: String?) {
guard let text = text, !text.isEmpty else {
print("Empty or nil string")
return
}
print(text.uppercased())
} uses a single guard with optional binding and emptiness check, then prints uppercase. func printUpper(_ text: String?) {
if let text = text, !text.isEmpty {
print(text.uppercased())
} else {
print("Empty or nil string")
}
} uses if-else, not guard. func printUpper(_ text: String?) {
guard text != nil else {
print("Empty or nil string")
return
}
print(text!.uppercased())
} only checks nil, not empty. func printUpper(_ text: String?) {
guard let text = text else {
print("Empty or nil string")
return
}
if text.isEmpty {
print("Empty or nil string")
}
print(text.uppercased())
} uses guard for nil, then if for empty that prints message but lacks return, so continues to print uppercased empty string, incorrect.
Final Answer:
guard let text = text, !text.isEmpty else { print("Empty or nil string"); return } print(text.uppercased()) -> Option A
Quick Check:
Guard with let and !isEmpty = correct early exit [OK]
Hint: Combine let binding and condition in one guard for clean code [OK]
Common Mistakes:
Checking only nil but not empty
Using if instead of guard for early exit
Splitting checks into multiple statements unnecessarily
Recommended
Ready to prove it?
Pass the test and this pattern moves unknownstrongwhile earning +1 Grip toward your certificate.