Bird
0
0

How can you merge two Swift dictionaries so that values from the second overwrite duplicates in the first?

hard📝 Application Q9 of 15
Swift - Collections
How can you merge two Swift dictionaries so that values from the second overwrite duplicates in the first?
let dict1 = ["a": 1, "b": 2]
let dict2 = ["b": 3, "c": 4]
// Fill in code here
Alet merged = dict1.union(dict2)
Blet merged = dict1 + dict2
Clet merged = dict1.merging(dict2) { (_, new) in new }
Dlet merged = dict1.append(contentsOf: dict2)
Step-by-Step Solution
Solution:
  1. Step 1: Use merging method with closure

    merging(_:uniquingKeysWith:) merges dictionaries, resolving duplicates with closure.
  2. Step 2: Provide closure to keep new values

    The closure { (_, new) in new } keeps the value from dict2 when keys duplicate.
  3. Final Answer:

    let merged = dict1.merging(dict2) { (_, new) in new } -> Option C
  4. Quick Check:

    Use merging with closure to combine dictionaries [OK]
Quick Trick: Use merging with closure to overwrite duplicate keys [OK]
Common Mistakes:
  • Using + operator (not supported)
  • Using union (not for dictionaries)
  • Trying append on dictionaries

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Swift Quizzes