Add or Append an Element to a Swift Dictionary
To add a key-value pair to a Swift dictionary, assign a value through the dictionary subscript using a new key.
myDictionary[new_key] = value
If new_key is not already present, Swift inserts a new key-value pair. If the key already exists, Swift replaces its current value instead of adding another entry.
The key and value must match the dictionary’s declared types. For example, a [String: Int] dictionary accepts a String key and an Int value.
How Swift Dictionary Insertion Works
A Swift dictionary stores one value for each unique key. Dictionaries do not provide an append() method like arrays because their elements are identified by keys rather than numeric positions.
- Assigning a value to a new key inserts an element.
- Assigning a value to an existing key updates that element.
- Assigning
nilthrough a dictionary subscript removes the key-value pair. - The order in which dictionary elements are printed or iterated should not be treated as fixed.
Example 1 – Append an Element to Swift Dictionary
In this example, we shall create a dictionary with some initial values, and append a new (key, value) pair to the dictionary.
main.swift
var myDictionary:[String:Int] = ["Mohan":75, "Raghu":82, "John":79]
myDictionary["Surya"] = 88
for (key, value) in myDictionary {
print("\(key) : \(value)")
}
Output
Raghu : 82
Mohan : 75
John : 79
Surya : 88
The assignment creates the key Surya and associates it with the value 88. The order of the printed entries may differ because dictionary iteration order should not be relied upon.
Add an Element to an Empty Swift Dictionary
The same subscript syntax can insert the first element into an empty dictionary.
var capitals = [String: String]()
capitals["India"] = "New Delhi"
print(capitals["India"] ?? "Not found")
print(capitals.count)
Output
New Delhi
1
After the assignment, the dictionary contains one key-value pair, so its count is 1.
Update an Existing Swift Dictionary Key
Using an existing key changes its value. It does not create a duplicate key or increase the dictionary count.
var productPrices = [
"Notebook": 50,
"Pen": 10
]
productPrices["Notebook"] = 60
print(productPrices["Notebook"] ?? 0)
print(productPrices.count)
Output
60
2
The value for Notebook changes from 50 to 60, while the number of dictionary entries remains 2.
Add or Update a Swift Dictionary Entry with updateValue()
The updateValue(_:forKey:) method also inserts a new entry or updates an existing one. It returns the previous value as an optional. The result is nil when the key did not previously exist.
var scores = ["Anu": 76]
let firstPreviousValue = scores.updateValue(84, forKey: "Ravi")
let secondPreviousValue = scores.updateValue(81, forKey: "Anu")
print(firstPreviousValue as Any)
print(secondPreviousValue as Any)
print(scores)
The first call adds Ravi, so there is no previous value. The second call replaces the value stored for Anu and returns 76.
Add Multiple Elements by Merging Swift Dictionaries
Use merge(_:uniquingKeysWith:) when several key-value pairs need to be added at once. The closure specifies which value to keep when both dictionaries contain the same key.
var inventory = [
"Pens": 10,
"Books": 5
]
let newStock = [
"Books": 8,
"Pencils": 12
]
inventory.merge(newStock) { current, new in
new
}
print(inventory["Books"] ?? 0)
print(inventory["Pencils"] ?? 0)
Output
8
12
The closure chooses the value from newStock when a duplicate key is found. Therefore, Books changes to 8, and Pencils is inserted as a new key.
Append a Value to an Array Stored in a Swift Dictionary
When dictionary values are arrays, use the default: subscript to append an item whether or not the key already exists.
var studentsByClass = [String: [String]]()
studentsByClass["Class A", default: []].append("Asha")
studentsByClass["Class A", default: []].append("Rahul")
studentsByClass["Class B", default: []].append("Meera")
print(studentsByClass["Class A"] ?? [])
print(studentsByClass["Class B"] ?? [])
Output
["Asha", "Rahul"]
["Meera"]
If the key is missing, the default empty array is inserted before the new value is appended. This avoids a separate check for whether the key already exists.
Swift Dictionary Add or Append Element FAQs
How do I append an element to a dictionary in Swift?
Assign a value to a new key, as in dictionary["key"] = value. Swift dictionaries do not use an array-style append() method for adding key-value pairs.
What happens when I add an existing key to a Swift dictionary?
The existing value is replaced. A dictionary cannot contain two separate entries with the same key.
How can I add several key-value pairs to a Swift dictionary?
Use merge(_:uniquingKeysWith:). Its conflict closure determines which value is retained when the dictionaries contain matching keys.
How do I append to an array value inside a Swift dictionary?
Use the default-value subscript, such as dictionary[key, default: []].append(item). It creates an empty array automatically when the key is absent.
Does adding an element preserve Swift dictionary order?
Dictionary code should not depend on insertion or iteration order. Sort the keys or key-value pairs explicitly when a predictable display order is required.
Swift Dictionary Element Insertion QA Checklist
- Confirm that new keys insert entries and existing keys update values.
- Verify that every inserted key and value matches the dictionary’s declared types.
- Do not describe dictionary insertion as position-based array appending.
- Use
mergewith an explicit duplicate-key rule when adding multiple entries. - Use the
default:subscript when appending to array values for keys that may be missing. - Avoid examples that depend on a fixed dictionary iteration order.
Summary of Adding Elements to a Swift Dictionary
Use subscript assignment to add a new key-value pair to a Swift dictionary. The same syntax updates the value when the key already exists. The updateValue() method is useful when the previous value is needed, merge() adds multiple entries, and the default-value subscript simplifies appending to array values. In this Swift Tutorial, we have covered each of these dictionary insertion patterns with examples.
TutorialKart.com