Problem overview
The function letterCount receives a string, word, and returns a dictionary that maps each letter to the number of times it appears. Only letters that occur become keys, and the order of the entries doesn't matter.
For "banana" the result holds three entries: "b" appears once, "a" three times and "n" twice. For "hello", "l" is 2 and every other letter is 1.
Approach: a counting dictionary
Counting how often things occur is one of the most common uses of a dictionary. Each distinct item is a key, and its value is the number of times the loop has seen it so far. At the start the dictionary is empty. For every letter, one of two things is true: the letter is already a key, so its count goes up by one, or it is new, so it enters the dictionary with a count of 1.
The type of the keys is Character, Swift's type for a single character. A for-in loop over a string produces its characters one at a time, so each loop variable is already a Character.
Step by step
- Create
countsas an empty[Character: Int]withvar, since it changes in the loop. - Loop over the string with
for letter in word. - Look up the letter with
if let count = counts[letter]. This runs the body only when the letter is already a key, and gives its current count a name. The body storescount + 1. - Handle the first sighting in the
elsebranch, wherecounts[letter]becomes 1. - Return
countsafter the loop.
The solution in Swift
class Solution {
func letterCount(_ word: String) -> [Character: Int] {
var counts: [Character: Int] = [:]
for letter in word {
if let count = counts[letter] {
counts[letter] = count + 1
} else {
counts[letter] = 1
}
}
return counts
}
}
Optionals and dictionaries
The key to this lesson is that a dictionary subscript returns an optional. counts[letter] has the type Int?: it holds the count when the key exists and is nil when it doesn't. A missing key is not an error, which is why a new letter can be detected with if let. The else branch runs exactly when the lookup gave nil.
Assigning through the subscript does two jobs. counts[letter] = 1 adds the key when it is absent, and counts[letter] = count + 1 replaces the value when it is present. The same assignment syntax covers both.
Swift also lets you shorten the whole branch with a default: counts[letter, default: 0] += 1 reads 0 for a missing key and then adds one. The lesson spells out both branches so the optional is visible. Reading a missing key without a default gives nil; for example, with a [Character: Int] dictionary that has no "z", counts["z"] is nil and counts["z", default: 0] is 0.
Edge cases and common mistakes
- Forcing the lookup with
!.counts[letter]! + 1crashes the program the first time a letter appears, because the value isnil. - Printing order. A Swift dictionary doesn't keep insertion order, and the order can change from one run to the next. The lesson's tests compare entries, not the order they print in.
- A single letter.
"a"gives one entry,"a": 1. - Letters that don't appear. They get no entry at all, not an entry with 0. Looking one up gives
nil. - Using
Stringkeys. The return type is[Character: Int]. A string key such as"a"in a literal is read as aCharacterwhen the dictionary's type says so.
Testing
Entries are listed in alphabetical order here for readability.
"banana"gives a: 3, b: 1, n: 2."hello"gives e: 1, h: 1, l: 2, o: 1."a"gives a: 1.
