Bird
0
0

Identify the error in this code snippet:

medium📝 Debug Q6 of 15
Swift - Optionals
Identify the error in this code snippet:
class House {
  var owner: String?
}

var house: House? = House()
print(house.owner?.count)
Aowner is optional, so optional chaining is needed on owner
BMissing optional chaining on house variable
CCannot use optional chaining on count property
DNo error, code is correct
Step-by-Step Solution
Solution:
  1. Step 1: Analyze property types

    house is optional, so house.owner needs optional chaining as house?.owner.
  2. Step 2: Check optional chaining on nested optional

    owner is optional String, so to access count, optional chaining is needed: house?.owner?.count.
  3. Final Answer:

    Missing optional chaining on house variable -> Option B
  4. Quick Check:

    Chain optionals at each level [OK]
Quick Trick: Chain ? for each optional level to avoid errors [OK]
Common Mistakes:
  • Forgetting optional chaining on nested optionals
  • Assuming one ? covers all optionals
  • Trying to access property directly on optional

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Swift Quizzes