Bird
0
0

What will be the output of this Swift code snippet?

medium📝 Predict Output Q4 of 15
iOS Swift - Swift Language Essentials
What will be the output of this Swift code snippet?
let speed: Int = 100
let time: Int? = nil
let distance = speed * (time ?? 0)
print(distance)
A0
B100
Cnil
DCompilation error
Step-by-Step Solution
Solution:
  1. Step 1: Understand the nil-coalescing operator usage

    time is nil, so (time ?? 0) evaluates to 0.
  2. Step 2: Calculate distance

    distance = speed * 0 = 100 * 0 = 0.
  3. Final Answer:

    0 -> Option A
  4. Quick Check:

    Nil-coalescing replaces nil with default [OK]
Quick Trick: ?? operator provides default for nil [OK]
Common Mistakes:
  • Expecting nil to propagate in multiplication
  • Thinking print outputs nil
  • Assuming compilation error due to optional

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More iOS Swift Quizzes