Challenge - 5 Problems
Swift Guard Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate2:00remaining
What is the output of this Swift code using guard?
Consider the following Swift function that uses a guard statement. What will be printed when calling checkNumber(5)?
Swift
func checkNumber(_ num: Int) { guard num > 10 else { print("Number is too small") return } print("Number is big enough") } checkNumber(5)
Attempts:
2 left
💡 Hint
Remember guard checks a condition and exits early if false.
✗ Incorrect
The guard statement checks if num > 10. Since 5 is not greater than 10, the else block runs, printing "Number is too small" and returning early.
❓ Predict Output
intermediate2:00remaining
What will this Swift function print when called with checkName(nil)?
Analyze the function below that uses guard to unwrap an optional String. What is the output of checkName(nil)?
Swift
func checkName(_ name: String?) { guard let unwrappedName = name else { print("No name provided") return } print("Hello, \(unwrappedName)!") } checkName(nil)
Attempts:
2 left
💡 Hint
Guard unwraps optionals safely.
✗ Incorrect
The guard statement tries to unwrap name. Since name is nil, the else block runs, printing "No name provided" and returning early.
🔧 Debug
advanced2:00remaining
Why does this Swift code cause a compile error?
Examine the code below. Why does it fail to compile?
Swift
func validateAge(_ age: Int?) { guard age != nil else { print("Age is missing") return } print("Age is \(age!)") } validateAge(nil)
Attempts:
2 left
💡 Hint
Remember guard requires exiting the current scope in else.
✗ Incorrect
The guard else block must exit the current scope (return, break, continue, throw). Here, it only prints but does not return, causing a compile error.
❓ Predict Output
advanced2:00remaining
What is the output of this Swift function using multiple guard statements?
Look at the function below. What will it print when called with processData(5, nil)?
Swift
func processData(_ x: Int?, _ y: Int?) { guard let a = x else { print("x is nil") return } guard let b = y else { print("y is nil") return } print("Sum is \(a + b)") } processData(5, nil)
Attempts:
2 left
💡 Hint
Each guard checks one optional and exits early if nil.
✗ Incorrect
The first guard unwraps x successfully (5). The second guard finds y is nil, so it prints "y is nil" and returns early.
🧠 Conceptual
expert2:00remaining
Why is the guard statement preferred for early exit in Swift functions?
Choose the best explanation for why Swift developers use guard statements for early exit.
Attempts:
2 left
💡 Hint
Think about how guard affects code structure and clarity.
✗ Incorrect
Guard statements help keep the main logic at the top level by exiting early on error or invalid conditions, reducing nested if-else blocks and improving readability.