Bird
0
0

Consider this Swift code:

medium📝 Predict Output Q5 of 15
Swift - Optionals
Consider this Swift code:
var number: Int! = nil
number = 42
print(number + 8)
What is the output?
ARuntime crash
BOptional(50)
C50
DCompile error
Step-by-Step Solution
Solution:
  1. Step 1: Analyze variable initialization and assignment

    The IUO number is initially nil but then assigned 42 before use.
  2. Step 2: Calculate the expression

    Since number is 42, adding 8 results in 50, which prints without error.
  3. Final Answer:

    50 -> Option C
  4. Quick Check:

    IUO with value unwraps safely = 50 [OK]
Quick Trick: IUO must have value before use to avoid crash [OK]
Common Mistakes:
  • Assuming crash because IUO was nil initially
  • Expecting Optional(50) output
  • Thinking compile error due to IUO

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Swift Quizzes