Bird
0
0

What will be printed when this Swift code runs?

medium📝 Predict Output Q4 of 15
Swift - Optionals
What will be printed when this Swift code runs?
func checkAge(_ age: Int?) {
    guard let age = age, age >= 18 else {
        print("Access denied")
        return
    }
    print("Access granted")
}
checkAge(nil)
checkAge(20)
AAccess granted\nAccess granted
BNo output
CAccess denied\nAccess denied
DAccess denied\nAccess granted
Step-by-Step Solution
Solution:
  1. Step 1: Analyze first call checkAge(nil)

    age is nil, guard let fails, else block runs printing "Access denied" and returns.
  2. Step 2: Analyze second call checkAge(20)

    age unwraps to 20, condition age >= 18 is true, so prints "Access granted".
  3. Final Answer:

    Access denied\nAccess granted -> Option D
  4. Quick Check:

    guard let with condition = correct output [OK]
Quick Trick: guard let with multiple conditions exits early if any fail [OK]
Common Mistakes:
  • Assuming nil passes guard
  • Ignoring condition after unwrapping
  • Expecting no output on nil

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Swift Quizzes