🎓 A1Learner
🔍
0 of 36 lessons completed

Swift Dictionary Default Values

A dictionary default value is a fallback that stands in for a key that is not stored. Writing a key with a default gives the stored value when one exists and the fallback when none exists.

Counting words with a default

Each word adds one through the default subscript, so a first sighting starts from zero. The counts print over the sorted keys.

var counts: [String: Int] = [:]
let words = ["cat", "dog", "cat", "bird", "dog", "cat"]
for word in words {
    counts[word, default: 0] += 1
}
for key in counts.keys.sorted() {
    print("\(key) \(counts[key, default: 0])")
}

Reading a missing key stores nothing

The fox key is read with a default of zero and prints as a plain number. The count stays at one after the read, and it still stays at one after reading the stored cat key.

var counts: [String: Int] = ["cat": 3]
print(counts["fox", default: 0])
print(counts.count)
print(counts["cat", default: 0])
print(counts.count)

Grouping words by first letter

Each word appends itself through the default subscript under its first letter, starting from an empty array. The groups print over the sorted keys.

var groups: [String: [String]] = [:]
let words = ["apple", "avocado", "banana", "berry", "cherry"]
for word in words {
    groups[String(word.prefix(1)), default: []].append(word)
}
for key in groups.keys.sorted() {
    print("\(key): \(groups[key, default: []])")
}

Counting letters in a word

The loop walks each letter of the word banana as a one letter string key. Each letter counts up through the default subscript.

var counts: [String: Int] = [:]
for letter in "banana" {
    counts[String(letter), default: 0] += 1
}
for key in counts.keys.sorted() {
    print("\(key) \(counts[key, default: 0])")
}

Example

var votes: [String: Int] = [:]
let ballots = ["Ana", "Ben", "Ana", "Cleo", "Ben", "Ana"]
for name in ballots {
    votes[name, default: 0] += 1
}
for key in votes.keys.sorted() {
    print("\(key) \(votes[key, default: 0])")
}
print(votes.count)

Key points

  • The default subscript reads a missing key as the given default value.
  • The value from a default subscript is a plain value, not an optional.
  • Adding with += through the default subscript starts a missing key from the default.
  • Reading a missing key with a default does not add an entry to the dictionary.
  • Appending through the default subscript groups values under their keys.

In this example, each ballot adds one to its name through the default subscript, so every first ballot for a name starts from zero. Ana appears three times, Ben appears twice, and Cleo appears once. The tallies print over the sorted keys, and the last line prints the count of distinct names, which is 3.

Note

Printing counted or grouped results over sorted keys keeps the printed order steady.

Try it Yourself

Edit the code, then press Run.

Running is simulated

Exercise

A program reads a missing key with a default of 0 and prints the result. What happens to the dictionary?