Bird
0
0

You have a class property declared as var data: String! which is set asynchronously after initialization. How should you safely use data in a method to avoid runtime crashes?

hard📝 Application Q15 of 15
Swift - Optionals
You have a class property declared as var data: String! which is set asynchronously after initialization. How should you safely use data in a method to avoid runtime crashes?
AForce unwrap <code>data!</code> without checking
BUse <code>print(data)</code> directly without checks
CChange <code>data</code> to a non-optional String
DUse <code>if data != nil { print(data) }</code> to check before use
Step-by-Step Solution
Solution:
  1. Step 1: Understand asynchronous setting of implicitly unwrapped optional

    Since data is set later, it may be nil when accessed early.
  2. Step 2: Use safe check before accessing

    Checking if data != nil ensures data is set before use, avoiding runtime crash.
  3. Final Answer:

    Use if data != nil { print(data) } to check before use -> Option D
  4. Quick Check:

    Check nil before using implicitly unwrapped optional set later [OK]
Quick Trick: Always check nil before using async-set implicitly unwrapped optional [OK]
Common Mistakes:
  • Using implicitly unwrapped optional without nil check
  • Changing type unnecessarily
  • Forcing unwrap without safety

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Swift Quizzes