SWIFT
Swift Dictionary: Syntax, Usage, and Examples
Dictionaries in Swift store key-value pairs, letting you map unique identifiers to specific data. They’re great for fast lookups, structured data organization, and counting or grouping information.
How to Define and Use a Dictionary
Create a dictionary using square brackets with a colon between key and value types:
Learn Swift on Mimo
Swift
var studentGrades: [String: Int] = ["Alice": 90, "Bob": 85, "Clara": 92]
You can also let Swift infer the types:
Swift
var capitals = ["France": "Paris", "Japan": "Tokyo", "India": "New Delhi"]
To create an empty dictionary:
Swift
var inventory: [String: Int] = [:]
Accessing and Updating Entries
Access a value by its key:
Swift
let grade = studentGrades["Alice"] // Output: Optional(90)
Since the key might not exist, the return type is optional.
Update or insert a value:
Swift
studentGrades["Bob"] = 88 // Update
studentGrades["Diana"] = 91 // Insert
Remove an entry:
Swift
studentGrades["Alice"] = nil
When to Use a Dictionary
Dictionaries are ideal for pairing identifiers with data. Common use cases include:
1. App Settings and Preferences
Swift
let settings = ["theme": "dark", "fontSize": "medium"]
2. Mapping IDs to Data
Swift
let users = [101: "Emma", 102: "Noah", 103: "Liam"]
3. Grouping by Category
Swift
let names = ["Alice", "Aaron", "Bob", "Becky"]
let grouped = Dictionary(grouping: names, by: { $0.prefix(1) })
// ["A": ["Alice", "Aaron"], "B": ["Bob", "Becky"]]
4. Counting Occurrences
Swift
let words = ["apple", "banana", "apple"]
var count: [String: Int] = [:]
for word in words {
count[word, default: 0] += 1
}
Examples
Create and Access Values
Swift
var countryCodes = ["US": "United States", "FR": "France", "JP": "Japan"]
print(countryCodes["FR"] ?? "Unknown")
Loop Through a Dictionary
Swift
let prices = ["apple": 1.2, "banana": 0.8, "cherry": 2.0]
for (fruit, price) in prices {
print("\(fruit): $\(price)")
}
Check for Existence
Swift
if let value = countryCodes["JP"] {
print("Found: \(value)")
} else {
print("Key not found.")
}
Use Default Values
Swift
let population = ["NY": 8_336_817]
let bostonPop = population["Boston", default: 0]
Advanced Dictionary Concepts
Ordered Dictionaries
Standard dictionaries don’t guarantee key order. In practice, insertion order is preserved (since Swift 5.2), but you shouldn’t rely on it.
To guarantee order, use OrderedDictionary from Swift Collections:
Swift
import OrderedCollections
var orderedDict: OrderedDictionary = ["first": 1, "second": 2]
orderedDict["third"] = 3
print(orderedDict[0]) // 1
Dictionary vs. Array
Use a dictionary when you:
- Need fast key-based lookups
- Want to group or count items
- Require unique keys
Use an array when you:
- Care about order
- Need to store duplicate values
- Plan to iterate over all elements in sequence
Filtering and Transforming
You can filter by value:
Swift
let scores = ["Amy": 95, "Ben": 82, "Chris": 99]
let highScorers = scores.filter { $0.value > 90 }
Transform values:
Swift
let bonusScores = scores.mapValues { $0 + 5 }
Transform keys and values:
Swift
let doubled = Dictionary(uniqueKeysWithValues: scores.map { ($0.key, $0.value * 2) })
Merging Dictionaries
Swift
var config = ["theme": "light", "volume": "low"]
let override = ["theme": "dark"]
config.merge(override) { (_, new) in new }
// ["theme": "dark", "volume": "low"]
Nested Dictionaries
Useful for modeling structured or API-style data:
Swift
let library = [
"fiction": ["1984": "Orwell", "Dune": "Herbert"],
"nonfiction": ["Sapiens": "Harari"]
]
if let author = library["fiction"]?["Dune"] {
print("Author of Dune: \(author)")
}
Optimizing Performance
If you expect to store many entries, reserve capacity to reduce reallocations:
Swift
var cache = [String: Int]()
cache.reserveCapacity(1000)
Converting to Arrays
Convert keys or values:
Swift
let sortedKeys = prices.keys.sorted()
let valuesArray = prices.values.map { $0 }
Sort by value:
Swift
let sortedByPrice = prices.sorted { $0.value < $1.value }
Summary
Dictionaries let you store and retrieve values efficiently using unique keys. They’re a go-to tool for counting, grouping, mapping, and organizing data in Swift. You can access, mutate, remove, and filter data with concise syntax and solid performance.
For more advanced scenarios, you can work with ordered dictionaries, nested structures, or use mapValues and filter for transformation. Swift’s dictionary type is both powerful and flexible—making it a core part of any well-structured app.
Join 35M+ people learning for free on Mimo
4.8 out of 5 across 1M+ reviews
Check us out on Apple AppStore, Google Play Store, and Trustpilot