Recall & Review
beginner
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:<br>
Allowed for 20 because age is valid and >= 18.<br>Not allowed for 15 because age is less than 18.<br>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?✗ 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?
✗ Incorrect
guard is designed for early exit when a condition is not met.What happens if the
guard condition is true?✗ Incorrect
If the
guard condition is true, the program continues normally after the guard statement.Why is
guard useful for unwrapping 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?✗ 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.