Back to questions
JuniorTheoryCommon
What does the program print?
let words = ["to", "be", "or", "not", "to", "be"]
var counts: [String: Int] = [:]
for word in words {
counts[word, default: 0] += 1
}
print(counts["be", default: 0], counts.count)2 4
- Expecting
1 4: readingdefault: 0as "set the count to 0". The default is used only while the key is missing; after that+= 1adds to the stored count. - Expecting
2 6: takingcountfor the number of words added. A dictionary counts pairs, and a repeated word updates its pair instead of adding one.
- What does
counts["is", default: 0]return here, and doescounts.countchange after it? - Why does
counts[word] += 1withoutdefault:not compile?