Counting entries with count
The count property of a dictionary is the number of key-value pairs it holds. It is a property, not a method, so you write scores.count with no parentheses.
var scores: [String: Int] = [:]
scores["Alice"] = 95
scores["Bob"] = 87
scores["Charlie"] = 72
let count = scores.count
print(count)
3
Each pair counts once. The keys alone and the values alone have the same number of elements, so scores.keys.count and scores.values.count are 3 as well.
Checking for empty
To ask whether there are any entries at all, use isEmpty. It reads better than comparing count with 0:
print(scores.isEmpty)
let empty: [String: Int] = [:]
print(empty.count)
print(empty.isEmpty)
false
0
true
How the count changes
The count follows the operations from the earlier lessons:
- Assigning to a new key adds a pair, so the count goes up by one.
- Assigning to an existing key replaces the value, so the count stays the same.
- Assigning
nilto a key removes the pair, so the count goes down by one if the key was there.
scores["Dan"] = 60
print(scores.count)
scores["Alice"] = 100
print(scores.count)
scores["Bob"] = nil
print(scores.count)
4
4
3
Because keys are unique, a dictionary literal with a repeated key is a mistake, and the program stops at run time when it is created. Build dictionaries from distinct keys.
Counting things with a dictionary
A common use of count is to see how many distinct items a dictionary has collected. Here a dictionary counts how often each character occurs in a string, and the number of entries is the number of distinct characters:
var counts: [Character: Int] = [:]
for ch in "hello" {
counts[ch, default: 0] += 1
}
print(counts["l"]!)
print(counts.count)
2
4
The word has five letters, but "l" appears twice, so there are four distinct keys. This is the difference between the size of the input and counts.count.
Removing a key also lowers the count, and the original is unaffected by removals on a copy: after var s = scores and s.removeValue(forKey: "Bob"), s.count is one less than scores.count.
Same name, same idea as arrays
Arrays also use count and isEmpty, so the habit carries over. For an array it counts elements, and for a dictionary it counts pairs. For [95, 87, 72] the count is 3, the same as for ["Alice": 95, "Bob": 87, "Charlie": 72]. Strings use count too, and it counts characters.
The exercise
The starter code gives a dictionary named scores with three students. One step is needed:
- Declare a constant
countwithletand assign itscores.count.
var scores: [String: Int] = ["Alice": 95, "Bob": 87, "Charlie": 72]
let count = scores.count
The constant holds 3, the number of pairs. It is a snapshot: if the dictionary changes later, count keeps the old number, and you read scores.count again to get the new one.
Common mistakes
- Adding parentheses.
scores.count()does not compile, becausecountis a property. - Using
lengthorsize. Other languages use those names. Swift usescount, and a dictionary has no property calledlength, so the compiler reports an error. - Confusing the count with a value.
scores.countis 3 even though the scores themselves are 95, 87 and 72.
Key takeaways
dict.countis the number of key-value pairs.dict.isEmptytells you whether there are none.- Adding a new key raises the count, replacing a value does not, and removing a key lowers it.
