Swift – Create Dictionary
A Swift dictionary stores key-value pairs. Each key identifies one value, and every key in a dictionary must be unique. You can create an empty dictionary, initialize one with values, build one from an array of pairs, and then add, read, update, or remove entries.
Dictionary keys must conform to Swift’s Hashable protocol. Common types such as String, Int, and Bool already conform to Hashable.
Swift Empty Dictionary Syntax
To create an empty dictionary in Swift, specify the key type and value type:
var myDict = [KeyType: ValueType]()
In this syntax:
myDictis the dictionary variable.KeyTypeis the data type used for keys.ValueTypeis the data type used for values.
The dictionary is declared with var because entries may be added or removed later. Use let when the dictionary must remain unchanged after initialization.
Create an Empty Swift Dictionary with Integer Keys and Values
The following statement creates an empty dictionary whose keys and values are both integers.
var myDict = [Int: Int]()
Create an Empty Swift Dictionary with String Keys and Values
The following statement creates an empty dictionary whose keys and values are strings.
var myDict = [String: String]()
The same dictionary type can also be written with the full Dictionary type name:
var myDict = [String: String]()
var names = Dictionary<String, String>()
Create a Swift Dictionary with Initial Key-Value Pairs
To create a dictionary with initial values, place comma-separated key-value pairs inside square brackets. A colon separates each key from its value.
var myDict:[KeyType: ValueType] = [key1:value1, key2:value2, .. , keyN:valueN]
In this syntax:
myDictis the dictionary variable.KeyTypespecifies the type of every key.ValueTypespecifies the type of every value.keyN:valueNrepresents a key-value pair.
Create a Swift Dictionary with Int Keys and Int Values
The following dictionary maps integer keys to integer values.
var myDict:[Int:Int] = [1:25, 2:54, 3:87]
Create a Swift Dictionary with Int Keys and String Values
The following dictionary uses integers as keys and strings as values.
var myDict:[Int:String] = [22:"Swift Tutorial", 12:"Tutorial Kart"]
Create a Swift Dictionary with String Keys and String Values
The following dictionary maps string identifiers to string values.
var myDict:[String:String] = ["as12":"Swift Tutorial", "mm24":"Tutorial Kart"]
Create a Swift Dictionary Using Type Inference
When the initial key-value pairs make the types clear, Swift can infer the dictionary type. The explicit [KeyType: ValueType] annotation is optional in such cases.
var capitals = [
"India": "New Delhi",
"Japan": "Tokyo",
"France": "Paris"
]
print(type(of: capitals))
Output
Dictionary<String, String>
All keys in a dictionary must use one compatible type, and all values must use one compatible type.
Add and Update Values in a Swift Dictionary
Assign a value to a key with subscript syntax. If the key does not exist, Swift adds a new entry. If the key already exists, its value is replaced.
var scores = ["Anita": 82, "Ravi": 75]
scores["Meera"] = 91
scores["Ravi"] = 80
print(scores["Meera"] as Any)
print(scores["Ravi"] as Any)
Output
Optional(91)
Optional(80)
You can also update an entry with updateValue(_:forKey:). This method returns the previous value as an optional, or nil when the key was not present.
var stock = ["Pen": 12]
let previousQuantity = stock.updateValue(18, forKey: "Pen")
print(previousQuantity as Any)
print(stock["Pen"] as Any)
Output
Optional(12)
Optional(18)
Get a Swift Dictionary Value for a Key
Dictionary lookup returns an optional because the requested key might not exist. Use optional binding to safely read a value.
let prices = ["Book": 250, "Bag": 900]
if let bookPrice = prices["Book"] {
print("Book price: \(bookPrice)")
} else {
print("Book was not found")
}
Output
Book price: 250
When a fallback value is appropriate, use the default: dictionary subscript.
let quantities = ["Apple": 5]
let appleCount = quantities["Apple", default: 0]
let orangeCount = quantities["Orange", default: 0]
print(appleCount)
print(orangeCount)
Output
5
0
Check Whether a Swift Dictionary Contains a Key
A dictionary contains a key when a lookup for that key returns a non-nil value.
let users = [101: "Asha", 102: "Vikram"]
if users[101] != nil {
print("Key 101 exists")
}
Output
Key 101 exists
Checking dictionary.keys.contains(key) is also possible, but a direct dictionary lookup is normally the clearer way to test for a key.
Access Swift Dictionary Keys and Values
Use the keys and values properties to access views of a dictionary’s keys and values. Convert them to arrays when an array is required.
let products = ["P01": "Keyboard", "P02": "Mouse"]
let productCodes = Array(products.keys)
let productNames = Array(products.values)
print(productCodes.count)
print(productNames.count)
Output
2
2
Do not rely on a dictionary’s iteration order. Sort the keys when output must appear in a predictable order.
let marks = ["Science": 88, "English": 81, "Maths": 94]
for subject in marks.keys.sorted() {
if let mark = marks[subject] {
print("\(subject): \(mark)")
}
}
Output
English: 81
Maths: 94
Science: 88
Remove a Key-Value Pair from a Swift Dictionary
Assign nil to a key or call removeValue(forKey:) to remove an entry. The method form returns the removed value as an optional.
var settings = ["theme": "dark", "language": "English"]
let removedValue = settings.removeValue(forKey: "theme")
settings["language"] = nil
print(removedValue as Any)
print(settings)
Output
Optional("dark")
[:]
Create a Swift Dictionary from an Array of Key-Value Tuples
Use Dictionary(uniqueKeysWithValues:) when an array contains key-value tuples and every key is unique.
let entries = [
("red", "#FF0000"),
("green", "#00FF00"),
("blue", "#0000FF")
]
let colorCodes = Dictionary(uniqueKeysWithValues: entries)
print(colorCodes["green"] as Any)
Output
Optional("#00FF00")
The uniqueKeysWithValues: initializer requires unique keys. When duplicate keys are possible, use Dictionary(_:uniquingKeysWith:) and provide a closure that chooses or combines the values.
let purchases = [
("Pen", 2),
("Book", 1),
("Pen", 3)
]
let totals = Dictionary(purchases, uniquingKeysWith: +)
print(totals["Pen"] as Any)
Output
Optional(5)
Swift Dictionary Creation and Usage Checklist
- Confirm that the dictionary key type conforms to
Hashable. - Use
varwhen entries need to be added, updated, or removed. - Use unique keys in dictionary literals and with
Dictionary(uniqueKeysWithValues:). - Handle dictionary lookups as optionals instead of force-unwrapping missing values.
- Use the
default:subscript when a missing key should return a fallback value. - Sort dictionary keys when predictable display order is required.
Swift Dictionary FAQs
Does Swift have a built-in dictionary type?
Yes. Swift provides the generic Dictionary<Key, Value> collection type. Its shorthand syntax is [Key: Value].
How do I create an empty dictionary in Swift?
Specify the key and value types and call the empty initializer, as in var scores = [String: Int](). You can also write var scores: [String: Int] = [:].
How do I add a key and value to a Swift dictionary?
Assign the value through the key subscript, such as scores["Asha"] = 95. Swift adds the entry when the key is new and updates the value when the key already exists.
Why does a Swift dictionary lookup return an optional?
The requested key may not exist. Swift therefore returns Value?, allowing the result to contain either a value or nil.
How do I remove a key from a Swift dictionary?
Call removeValue(forKey:) or assign nil to the key subscript. The removal method returns the previous value when the key exists.
Creating Dictionaries in Swift: Key Points
In this Swift Tutorial, we learned how to create an empty dictionary, initialize a dictionary with key-value pairs, use type inference, create a dictionary from an array, and perform common dictionary operations. Remember that keys must be unique and hashable, while dictionary lookups return optional values because a key may be absent.
TutorialKart.com