Bird
0
0

What will be the output of this Swift code?

medium📝 Predict Output Q4 of 15
Swift - Optionals
What will be the output of this Swift code?
var number: Int? = 5
if let value = number {
  print(value * 2)
} else {
  print("No value")
}
AOptional(5)
BNo value
C10
DRuntime error
Step-by-Step Solution
Solution:
  1. Step 1: Check optional binding

    The variable number holds 5, so if let unwraps it into value = 5.
  2. Step 2: Calculate and print

    Inside the if block, value * 2 = 10 is printed.
  3. Final Answer:

    10 -> Option C
  4. Quick Check:

    Unwrapped value multiplied = 10 [OK]
Quick Trick: if let unwraps and uses the value safely [OK]
Common Mistakes:
  • Expecting 'No value' when optional has a value
  • Printing Optional(5) instead of unwrapped value
  • Assuming runtime error from optional

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Swift Quizzes