Dictionary Default Subscripts
Read dictionary values with built-in defaults.
Dictionary Default Subscripts is a free Swift Academy lesson on CoddyKit — lesson 4 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the Swift Academy learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.
Dictionary Lookups Are Optional
Looking up a key with dict[key] returns an optional, because the key might not exist. That optional needs handling.
let ages = ["Ann": 30]
let bob = ages["Bob"]
print(bob as Any)The Default Subscript
Swift offers a subscript with a default: dict[key, default: value]. If the key is missing, you get the default instead of nil.
let ages = ["Ann": 30]
print(ages["Bob", default: 0])
print(ages["Ann", default: 0])Result Is Non-Optional
Unlike a plain lookup, the default subscript returns a non-optional value, so you can use it immediately without unwrapping.
let stock = ["pen": 5]
let pens: Int = stock["pen", default: 0]
print(pens + 1)Counting With Defaults
The default subscript shines when counting occurrences. Start each key at 0 and add as you go.
var counts: [String: Int] = [:]
let words = ["a", "b", "a", "a", "b"]
for word in words {
counts[word, default: 0] += 1
}
print(counts["a", default: 0])
print(counts["b", default: 0])Why += Works
Because dict[key, default: 0] yields a real value even for a new key, you can mutate it in place with += safely.
var tally: [String: Int] = [:]
tally["x", default: 0] += 5
tally["x", default: 0] += 3
print(tally["x", default: 0])Grouping Sums
You can accumulate sums per category in a single pass using the default subscript.
let sales = [("apple", 3), ("pear", 2), ("apple", 4)]
var totals: [String: Int] = [:]
for (item, amount) in sales {
totals[item, default: 0] += amount
}
print(totals["apple", default: 0])Default vs Nil Coalescing
dict[key, default: 0] is equivalent to dict[key] ?? 0 for reading, but the subscript form also supports in-place mutation.
let prices = ["tea": 3]
print(prices["tea"] ?? 0)
print(prices["tea", default: 0])Appending to Array Values
The default subscript works with array values too, letting you build grouped lists.
var groups: [String: [Int]] = [:]
groups["even", default: []].append(2)
groups["even", default: []].append(4)
print(groups["even", default: []])Defaults Do Not Insert
Reading with a default does not add the key to the dictionary. Only when you mutate (like +=) is the key stored.
var data: [String: Int] = [:]
_ = data["ghost", default: 0]
print(data.count)
data["real", default: 0] += 1
print(data.count)Choosing a Sensible Default
Pick a default that matches the value type and the operation: 0 for sums, [] for lists, an empty string for text.
var notes: [String: String] = [:]
notes["greeting", default: ""] += "Hello"
notes["greeting", default: ""] += " World"
print(notes["greeting", default: ""])Combining Counts and Reads
Build a frequency map, then read it back with the same default to stay non-optional throughout.
var freq: [Character: Int] = [:]
for ch in "banana" {
freq[ch, default: 0] += 1
}
print(freq["a", default: 0])
print(freq["z", default: 0])Quick Check
Test the default subscript.
Recap: Dictionary Default Subscripts
Use dict[key, default: value] to read a non-optional fallback and to mutate values in place. It is ideal for counting, summing, and grouping without manual nil checks.
var c: [String: Int] = [:]
for x in ["a", "a", "b"] { c[x, default: 0] += 1 }
print(c["a", default: 0])Frequently asked questions
Is the “Dictionary Default Subscripts” lesson free?
Yes — the full text of “Dictionary Default Subscripts” is free to read here on the web, and the Swift Academy course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the Swift Academy course, upgrade to CoddyKit PRO.
What will I learn in “Dictionary Default Subscripts”?
Read dictionary values with built-in defaults. You practise Swift Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.
Do I need any experience to start Swift Academy?
No prior experience is required. Swift Academy on CoddyKit is structured for beginners through advanced learners; this is — lesson 4 of 4, so you can start here or from the beginning and move at your own pace.
How long does the “Dictionary Default Subscripts” lesson take?
Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.
Can I write and run code in this Swift Academy lesson?
Yes. Every Swift Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.
All lessons in this course
- The Nil-Coalescing Operator
- Chaining Default Values
- Defaults in Function Parameters
- Dictionary Default Subscripts