Concept Flow - Guard for early exit pattern
Start function
Evaluate guard condition
Continue
Rest of [Return or break
The guard statement checks a condition early. If false, it exits the function immediately. Otherwise, the code continues.
func checkAge(age: Int) { guard age >= 18 else { print("Too young") return } print("Welcome") }
| Step | age | guard condition (age >= 18) | Branch taken | Action | Output |
|---|---|---|---|---|---|
| 1 | 16 | False | No (early exit) | Print "Too young" and return | Too young |
| 2 | 20 | True | Yes (continue) | Print "Welcome" | Welcome |
| Variable | Start | After Step 1 | After Step 2 | Final |
|---|---|---|---|---|
| age | input | 16 | 20 | 20 |
guard condition else {
// exit early (return, break)
}
- Checks condition early
- If false, exits function immediately
- Keeps main code less nested
- Used for input validation or safetyguard statements in Swift?guardguard is used to check a condition and exit the current scope early if the condition is false.guard.guard statement in Swift?guardguard condition else { ... } where the else block handles the early exit.guard condition else { return } matches the correct syntax. Options A, B, and D have missing else, extra parentheses, or misplaced keywords.func checkAge(_ age: Int?) {
guard let age = age, age >= 18 else {
print("Access denied")
return
}
print("Access granted")
}
checkAge(nil)
checkAge(16)
checkAge(21)age is not nil and at least 18. If false, it prints "Access denied" and returns early.checkAge(nil), age is nil -> prints "Access denied".checkAge(16), age is 16 < 18 -> prints "Access denied".checkAge(21), age is 21 ≥ 18 -> prints "Access granted".guard:func greet(name: String?) {
guard name != nil else {
print("No name provided")
}
print("Hello, \(name!)")
}guard, which code snippet correctly implements this behavior?Pass the test and this pattern moves unknown