- API fetch
- Array
- Async await
- Class
- Closures
- Computed property
- Concurrency
- Constants
- Data types
- Defer statement
- Dictionary
- Enum
- Escaping closure
- Extension
- For loop
- forEach
- Function
- Generics
- Guard statement
- if let statement
- Inheritance
- inout
- Lazy var
- Operator
- Optionals
- Property observers
- Property wrapper
- Protocol
- String formatting
- String interpolation
- Struct
- Switch statement
- Try catch
- Tuple
- Variables
- While loop
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:
var studentGrades: [String: Int] = ["Alice": 90, "Bob": 85, "Clara": 92]
You can also let Swift infer the types:
var capitals = ["France": "Paris", "Japan": "Tokyo", "India": "New Delhi"]
To create an empty dictionary:
var inventory: [String: Int] = [:]
Accessing and Updating Entries
Access a value by its key:
let grade = studentGrades["Alice"] // Output: Optional(90)
Since the key might not exist, the return type is optional.
Update or insert a value:
studentGrades["Bob"] = 88 // Update
studentGrades["Diana"] = 91 // Insert
Remove an entry:
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
let settings = ["theme": "dark", "fontSize": "medium"]
2. Mapping IDs to Data
let users = [101: "Emma", 102: "Noah", 103: "Liam"]
3. Grouping by Category
let names = ["Alice", "Aaron", "Bob", "Becky"]
let grouped = Dictionary(grouping: names, by: { $0.prefix(1) })
// ["A": ["Alice", "Aaron"], "B": ["Bob", "Becky"]]
4. Counting Occurrences
let words = ["apple", "banana", "apple"]
var count: [String: Int] = [:]
for word in words {
count[word, default: 0] += 1
}
Examples
Create and Access Values
var countryCodes = ["US": "United States", "FR": "France", "JP": "Japan"]
print(countryCodes["FR"] ?? "Unknown")
Loop Through a Dictionary
let prices = ["apple": 1.2, "banana": 0.8, "cherry": 2.0]
for (fruit, price) in prices {
print("\(fruit): $\(price)")
}
Check for Existence
if let value = countryCodes["JP"] {
print("Found: \(value)")
} else {
print("Key not found.")
}
Use Default Values
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:
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:
let scores = ["Amy": 95, "Ben": 82, "Chris": 99]
let highScorers = scores.filter { $0.value > 90 }
Transform values:
let bonusScores = scores.mapValues { $0 + 5 }
Transform keys and values:
let doubled = Dictionary(uniqueKeysWithValues: scores.map { ($0.key, $0.value * 2) })
Merging Dictionaries
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:
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:
var cache = [String: Int]()
cache.reserveCapacity(1000)
Converting to Arrays
Convert keys or values:
let sortedKeys = prices.keys.sorted()
let valuesArray = prices.values.map { $0 }
Sort by value:
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.
Sign up or download Mimo from the App Store or Google Play to enhance your programming skills and prepare for a career in tech.