Swift
Dictionary
Combine Dictionaries
iOS Development
Programming Tips

How can I combine two Dictionary instances in Swift?

Data Structures & Algorithms practice on Codemia

Step through 300 algorithm problems with animated visualisers that show the data structure changing as the code runs.

Practice algorithms

Introduction

In Swift, combining two dictionaries is straightforward once you decide what should happen when both dictionaries contain the same key. Swift gives you both mutating and non-mutating APIs for this, and the conflict-resolution closure is the part that determines the real behavior.

Use merge to Modify an Existing Dictionary

If you want to update one dictionary in place, use merge.

swift
1import Foundation
2
3var base = [
4    "host": "localhost",
5    "port": "5432"
6]
7
8let override = [
9    "port": "5433",
10    "database": "appdb"
11]
12
13base.merge(override) { current, new in
14    new
15}
16
17print(base)

This keeps the value from override whenever the same key appears in both dictionaries.

The conflict closure matters only when keys collide. If a key exists in just one dictionary, it is copied directly.

Use merging to Create a New Dictionary

If you want to keep both originals unchanged, use merging.

swift
1import Foundation
2
3let defaults = [
4    "theme": "light",
5    "pageSize": "20"
6]
7
8let userSettings = [
9    "pageSize": "50",
10    "language": "en"
11]
12
13let combined = defaults.merging(userSettings) { current, new in
14    new
15}
16
17print(defaults)
18print(userSettings)
19print(combined)

This is the better choice when you want an immutable result or you are composing values in a functional style.

Choosing Which Value Wins

The merge closure defines the rule for duplicate keys. The two most common policies are:

  • keep the new value
  • keep the existing value

Keep the new value:

swift
let result = defaults.merging(userSettings) { _, new in new }

Keep the existing value:

swift
let result = defaults.merging(userSettings) { current, _ in current }

That makes the API flexible enough to express configuration layering, user overrides, caching, and other common patterns.

Merging Numeric or Aggregate Values

The closure does not have to choose one side unchanged. It can combine values however you need.

swift
1import Foundation
2
3let january = [
4    "apples": 10,
5    "oranges": 5
6]
7
8let february = [
9    "apples": 7,
10    "bananas": 3
11]
12
13let totals = january.merging(february) { current, new in
14    current + new
15}
16
17print(totals)

This is useful when dictionaries represent counts, totals, or metrics rather than simple replacement values.

Combining More Than Two Dictionaries

If you need to merge several dictionaries, reduce(into:) scales better than chaining many calls by hand.

swift
1import Foundation
2
3let layers = [
4    ["timeout": 10, "retries": 1],
5    ["timeout": 20],
6    ["retries": 3, "cache": 1]
7]
8
9let merged = layers.reduce(into: [String: Int]()) { partialResult, next in
10    partialResult.merge(next) { _, new in new }
11}
12
13print(merged)

This pattern is clean when building configuration from defaults, environment overrides, and user overrides.

Think About Semantics, Not Just Syntax

The technical merge is easy. The real design question is what duplicate keys mean in your domain.

Examples:

  • configuration layering usually keeps the new value
  • cached values may keep the existing value
  • metrics or counters may sum the values

Choosing the closure deliberately is more important than memorizing whether the method name ends in -ing.

Performance and Type Notes

Swift dictionaries are value types, but they use copy-on-write semantics. That means merging does not immediately duplicate everything just because you assign the result to a new variable. It remains efficient in typical use.

Still, if you already own a mutable dictionary and want to update it, merge communicates the intent more directly and avoids creating a separate result variable.

Common Pitfalls

The biggest mistake is forgetting that duplicate keys require a conflict-resolution closure. Swift makes you choose because there is no universally correct default.

Another mistake is using merge when the original dictionary should stay unchanged. In that case, merging is the clearer API.

Developers also sometimes assume dictionaries preserve insertion order as a design guarantee they can build logic around. Dictionary ordering is not the right abstraction for configuration semantics.

Finally, think about value type compatibility. Both dictionaries must have the same key and value types unless you transform them before merging.

Summary

  • Use merge to update an existing dictionary in place.
  • Use merging to create a new combined dictionary without mutating the originals.
  • The conflict-resolution closure decides what happens for duplicate keys.
  • That closure can keep the old value, keep the new value, or combine both values.
  • For several dictionaries, reduce(into:) plus merge is a clean scalable pattern.

Related reading
Course
Intermediate
27 lessons
15 hours
DSA Fundamentals

Master algorithmic patterns and data structures through hands-on LeetCode-style problems - from arrays and hashing to dynamic programming and advanced graphs.

View the course
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

Data Structures & Algorithms practice on Codemia

Step through 300 algorithm problems with animated visualisers that show the data structure changing as the code runs.

Practice algorithms

All Rights Reserved.