Menu
Coddy logo textTech

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 icon

Challenge

Medium

Read a single line of input: a comma-separated list of words.

Print, in this order:

  1. One line per word length that appears in the input, sorted from shortest to longest, in the format <length>: <count> where count is how many words of that length appeared
  2. Most common length: <n> where n is 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)
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Logic & Flow