Bird
0
0

What will be printed by this Swift code?

medium📝 Predict Output Q4 of 15
Swift - Optionals
What will be printed by this Swift code?
var age: Int? = 25
if let actualAge = age {
    print("Age is \(actualAge)")
} else {
    print("Age is unknown")
}
Anil
BAge is unknown
CAge is 25
DError: Optional not unwrapped
Step-by-Step Solution
Solution:
  1. Step 1: Check the optional value

    The variable age contains 25, so it is not nil.
  2. Step 2: Optional binding with if let

    The if let unwraps age into actualAge and enters the if block.
  3. Final Answer:

    Age is 25 -> Option C
  4. Quick Check:

    Non-nil optional prints unwrapped value [OK]
Quick Trick: If optional has value, if let block runs [OK]
Common Mistakes:
  • Assuming else block runs when optional has value
  • Forgetting to unwrap optional
  • Expecting nil to print

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Swift Quizzes