Grouping Values
Part of the Logic & Flow section of Coddy's Swift journey — lesson 16 of 56.
The default-subscript pattern is the foundation for two everyday shapes.
Frequency counter: count how many times each key appears.
let letters = ["a", "b", "a", "c", "a"]
var counts: [String: Int] = [:]
for letter in letters {
counts[letter, default: 0] += 1
}
// counts == ["a": 3, "b": 1, "c": 1]Bucketing: collect values under a derived key:
let words = ["hi", "hello", "yo", "hey"]
var byLength: [Int: [String]] = [:]
for w in words {
byLength[w.count, default: []].append(w)
}
// [2: ["hi", "yo"], 5: ["hello"], 3: ["hey"]]The default for the bucketing case is an empty array. The default: value is used only when the key is missing, then the right-hand side mutates the entry in place.
Challenge
MediumRead a single line of input: a comma-separated list of words.
Print, in this order:
- One line per word length that appears in the input, sorted from shortest to longest, in the format
<length>: <count>wherecountis how many words of that length appeared Most common length: <n>wherenis the length with the highest count. Break ties by picking the shorter length.
For input hi,hello,yo,hey,bonjour,bye, the output is:
2: 2
3: 2
5: 1
7: 1
Most common length: 2(Lengths 2 and 3 both appear twice. Tie broken by shorter, so 2 wins.)
Cheat sheet
Frequency counter – count occurrences of each key using default: 0:
var counts: [String: Int] = [:]
for letter in letters {
counts[letter, default: 0] += 1
}Bucketing – group values under a derived key using default: []:
var byLength: [Int: [String]] = [:]
for w in words {
byLength[w.count, default: []].append(w)
}The default: value is only used when the key is missing; the result is then mutated in place.
Try it yourself
let words = readLine()!.components(separatedBy: ",")
// TODO: count words per length; print sorted; print most common (ties: shorter)
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Logic & Flow
1Strings In Depth
Count and IndicesCase and TrimSearching in StringsSplitting and JoiningReplacing SubstringsRecap - Username Check3Dictionaries
Declaring DictionariesOptional LookupUpdating DictionariesIterating DictionariesGrouping ValuesRecap - Inventory