Bird
0
0

You have a dictionary of user IDs to optional email addresses:

hard📝 Application Q8 of 15
Swift - Optionals
You have a dictionary of user IDs to optional email addresses:
let emails: [Int: String?] = [1: "a@example.com", 2: nil, 3: "c@example.com"]

How can you safely create a new dictionary mapping user IDs to non-optional emails, excluding users without emails?
AUse mapValues and force unwrap all emails
BUse compactMapValues to unwrap and filter nil values
CUse filter to remove nil emails but keep optionals
DUse flatMap to flatten the dictionary
Step-by-Step Solution
Solution:
  1. Step 1: Understand dictionary with optional values

    Values are optional strings; some are nil and should be excluded.
  2. Step 2: Use compactMapValues

    This method unwraps optionals and removes entries with nil values, producing non-optional values.
  3. Final Answer:

    Use compactMapValues to unwrap and filter nil values -> Option A
  4. Quick Check:

    compactMapValues unwraps and filters nil = B [OK]
Quick Trick: compactMapValues unwraps optionals and drops nils [OK]
Common Mistakes:
  • Force unwrapping causing crashes
  • Filtering but keeping optionals
  • Using flatMap incorrectly on dictionaries

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Swift Quizzes