Bird
0
0

You have an optional dictionary [String: Int?] and want to safely print the value for key "score" using force unwrapping. Which code safely avoids a crash?

hard📝 Application Q8 of 15
Swift - Optionals
You have an optional dictionary [String: Int?] and want to safely print the value for key "score" using force unwrapping. Which code safely avoids a crash?
Aprint(dict["score"]!)
Bif let dict = dict, let val = dict["score"] { print(val!) }
Cprint(dict!["score"]!)
Dprint(dict["score"] ?? 0)
Step-by-Step Solution
Solution:
  1. Step 1: Understand dictionary optional and nested optional

    The dictionary itself and its values are optional, so multiple unwraps needed.
  2. Step 2: Analyze options for safe unwrapping

    if let dict = dict, let val = dict["score"] { print(val!) } uses optional binding to unwrap dictionary and value safely before force unwrapping inner optional.
  3. Final Answer:

    if let dict = dict, let val = dict["score"] { print(val!) } -> Option B
  4. Quick Check:

    Safe nested unwrap = optional binding + force unwrap inner [OK]
Quick Trick: Use optional binding before force unwrapping nested optionals [OK]
Common Mistakes:
  • Force unwrapping dictionary or value directly
  • Ignoring nested optional structure
  • Using ?? without unwrapping inner optional

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Swift Quizzes