Menu
Coddy logo textTech

Mark Done

Part of the Logic & Flow section of Coddy's Swift journey — lesson 34 of 56.

The first feature: process a list of "mark this habit done on this day" actions and produce a final state.

Each input line is one operation in the format habit:day where day is between 1 and 7. If the habit doesn't exist yet, create it with an empty array, then append the day. If a day is already recorded for that habit, do not record it twice.

You'll lean on the default-subscript pattern from the dictionary chapter: habits[name, default: []].append(day) works whether the key exists or not.

challenge icon

Challenge

Easy

Read a single line of input: a comma-separated list of habit:day entries (e.g. read:1,read:3,workout:2). After applying every operation, print the habits in alphabetical order, one per line, in the format:

<habit>: <days_sorted_ascending_joined_with_comma>

Skip duplicate habit:day pairs.

For input read:1,read:3,workout:2,read:1,read:5,workout:4, the output is:

read: 1,3,5
workout: 2,4

Cheat sheet

Use the default-subscript pattern to append to a dictionary of arrays, creating the key if it doesn't exist:

var habits: [String: [Int]] = [:]
habits[name, default: []].append(day)

To avoid duplicates, check before appending:

if !habits[name, default: []].contains(day) {
    habits[name, default: []].append(day)
}

Try it yourself

var habits: [String: [Int]] = [:]
let ops = readLine()!.components(separatedBy: ",")

// TODO: for each op, parse name:day, append day if not already there;
// then print habits in alphabetical order with sorted days
quiz iconTest yourself

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

All lessons in Logic & Flow