Bird
0
0

What will be the output of this Swift code?

medium📝 Predict Output Q4 of 15
iOS Swift - Swift Language Essentials
What will be the output of this Swift code?
var temperature: Int? = nil
if let temp = temperature {
  print("Temp is \(temp)")
} else {
  print("Temperature unknown")
}
ATemp is 0
BTemperature unknown
CRuntime error
DTemp is nil
Step-by-Step Solution
Solution:
  1. Step 1: Analyze the Optional variable

    The variable temperature is an Optional Int initialized to nil.
  2. Step 2: Understand optional binding

    The if let statement unwraps temperature safely. Since it is nil, the else block executes.
  3. Final Answer:

    Temperature unknown -> Option B
  4. Quick Check:

    Nil Optional triggers else block in if let [OK]
Quick Trick: If Optional is nil, if let else block runs [OK]
Common Mistakes:
  • Assuming nil unwraps to 0
  • Expecting a runtime error
  • Printing 'Temp is nil' which is invalid

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More iOS Swift Quizzes