Bird
0
0

Identify the error in this Swift code:

medium📝 Debug Q6 of 15
Swift - Optionals
Identify the error in this Swift code:
var value: Int?
value = 5
print(value!)
AOptional variable cannot be assigned a value
BForce unwrapping without checking nil can cause runtime error
CMissing declaration of value as non-optional
DSyntax error in variable declaration
Step-by-Step Solution
Solution:
  1. Step 1: Analyze force unwrapping usage

    Using value! force unwraps the optional without checking if it is nil.
  2. Step 2: Check if value is nil before unwrapping

    Since value is assigned 5, force unwrap works here, but if it were nil, it would cause a runtime error.
  3. Final Answer:

    Force unwrapping without checking nil can cause runtime error -> Option B
  4. Quick Check:

    Force unwrap risky without nil check [OK]
Quick Trick: Always check nil before force unwrapping optionals [OK]
Common Mistakes:
  • Assuming force unwrap is always safe
  • Confusing optional assignment rules
  • Ignoring runtime error risk

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Swift Quizzes