Skip to content
Tutorials Center
My learning

Topics

Lesson 134 of 146 ยท Projects

Project: Command-Line To-Do Manager

Build a to-do manager in Swift with structs, enums, typed errors, a command parser and Codable JSON persistence behind a storage protocol. A complete program that runs in your browser.

A to-do list is the classic first project, and it is a good one because it contains the shape of most real applications: a model (the data), operations on it that can fail, a text interface that turns user input into actions, and persistence that keeps the data between runs. In this project you build all four in Swift, using value types and the standard library, and finish with a complete program that you can drive from the Input box.

You will practice structs and enums for the model, typed throws for errors, Codable for saving, a protocol to hide where the data is stored, and sorting and dictionaries for the reports. If one of these feels shaky, follow the link and come back.

The plan

A good way to start a program is to write down the commands a user would type. Ours looks like this:

TEXT
add Buy milk !high #shopping    create an item with a priority and tags
list [open|done|all] [#tag]     show items, optionally filtered
done 3     undo 3     remove 3  change or delete an item by its number
rename 2 New title              change the title
find word                       search titles
stats                           counts by status, priority and tag
save   load   export            persistence and a JSON dump

We then split the program into layers, each with one job, and build them from the inside out:

  1. TodoItem and TodoList: the model and its rules. No printing, no input, no files.
  2. Storage and TodoRepository: saving and loading the list as JSON.
  3. Command: turning one line of text into a value that describes what to do.
  4. TodoApp: running a command against the list and producing output lines.
  5. The main loop: readLine() in, print out.

The model never prints. Every layer returns values, and only the last layer talks to the console. This is what lets you test the first four layers without a terminal, and swap the console for a web page or a GUI later.

Step 1: the model

Each item has a number, a title, a priority, some tags and a done flag. A struct is the right tool: an item is plain data, copying it is cheap, and equality should compare the contents. The priority is a small enum with string raw values, which also makes the JSON readable:

Swift Step 1: items and priorities as Codable values

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

Three things happen here without any code of ours. Because every stored property is itself Codable, the compiler synthesizes the encoding and decoding. Because the properties are Equatable, the == is synthesized too. And Comparable on the enum is the one piece we write by hand, using a private rank so that the order is low < normal < high regardless of how the cases are spelled. The copy copy stays unchanged when milk changes: that is value semantics, and you rely on it every time you pass an item to a function.

sortedKeys makes the JSON key order stable, which matters for tests and for readable diffs of saved files. Without it, the key order of a JSONEncoder can differ from run to run.

Step 2: the list and its rules

The list owns the items and enforces the rules: a title cannot be empty, an item that does not exist cannot be completed, and numbers are never reused. It also keeps the counter for the next number. All the ways an operation can fail go into one error enum, which we declare typed, so callers know exactly what to handle:

Swift Step 2: a list with typed errors

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

Look at how the types protect the design. items is private(set), so outside code can read the list but only the methods above can change it; nobody can append an item with a duplicate number. position(of:) is the single place that turns a number into an index, so "not found" is handled once. And sortedItems is a computed property rather than a stored array: the order can never get out of date, because it is computed on demand. For a few hundred items, sorting on every call is instantaneous; if you had a million, you would cache it.

add is marked @discardableResult, because most callers ignore the item it returns. The last two do blocks show the payoff of typed throws: the first catch receives a TodoError, and the second block can write catch .emptyTitle as a pattern without casting. The order matters: patterns are tried top to bottom, and a final plain catch is needed unless the list of patterns is exhaustive.

What if you forget the var? Mutating methods are rejected on constants, with a message every Swift programmer learns to read:

Swift Mutating a constant list (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

The compiler reports error: cannot use mutating member on immutable value: 'list' is a 'let' constant and suggests changing the declaration to var. With structs, the let is not just a promise about the name: it freezes the whole value.

Step 3: saving and loading

Where does the list live between runs? On a real computer, in a file; in a test, in memory; in a mobile app, maybe in the cloud. The list itself should not care. We define a small protocol for storage and write the repository against the protocol, not against a particular place:

Swift Step 3: a storage protocol, memory and file implementations

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

Notice what the protocol buys. demo runs the same code against two completely different places and prints the same story. A unit test would use MemoryStorage and never touch the disk. The repository is the only code that knows about JSON; the Storage implementations only know about bytes.

Failures are a fact of life with files, and the last example shows the interesting one: the data exists but is damaged. JSONDecoder throws a DecodingError, and the case keyNotFound tells you which key was missing. In the full program we will not let such errors crash anything; they become a friendly message.

Saving by overwriting a file in place can destroy the only good copy if the program dies halfway through the write. For real data, write to a temporary file and rename it over the old one. Data.write(to:options:) with the .atomic option does exactly that.

Step 4: the complete program

The remaining layers are the command parser and the application that runs commands. A Command enum describes every action as data, and a static parse function turns a line into one, throwing a typed error for everything that can be wrong with the input. The rest of the program has no string handling at all, which is the main benefit of parsing first.

The program below is complete. The Input box holds a script of commands, including mistakes on purpose, a save followed by changes and a load that brings the saved state back. Read the program top to bottom, then the output.

Swift Step 4: the complete to-do manager

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

Follow one command through the layers to see how they fit. The line add Plan trip #work #travel !high goes to Command.parse, which splits it into words and sorts them by their first character into a title, tags and a priority. The result is .add(title: "Plan trip", priority: .high, tags: ["work", "travel"]). TodoApp.execute switches on the command, calls list.add, and returns the lines to print. Only the main loop prints.

A few decisions are worth a second look:

  • Errors from different layers become one type. The repository catches whatever JSONEncoder or Storage throws (untyped errors) and rethrows TodoError.storage, a typed error with a message we control. A function declared throws(TodoError) cannot leak any other error, so the catch in the main loop is a complete handler.
  • execute returns [String] instead of printing. A test can compare the lines with ==.
  • Sorting with tuples. In statistics, ($0.value, $1.key) > ($1.value, $0.key) sorts the tags by count descending and then by name ascending. Swapping key between the two sides reverses just that part. Tuples up to six elements compare lexicographically when all elements are Comparable.
  • list.sortedItems(matching: filter) passes filter.accepts as a function value to filter. Methods are closures in disguise, which is the idea from function types.
  • localizedCaseInsensitiveContains makes find trip match "Plan trip" whatever the case.

Dictionary order is random in Swift. That is why statistics sorts the tag counts before printing. If you print a dictionary directly, the line order can change from one run to the next, which is a terrible property for a command-line tool and for its tests.

Ideas for extending it

  • Due dates: add due: Date? to the item, a due command, and a list overdue filter. Use ISO 8601 text in the JSON, which JSONEncoder supports through dateEncodingStrategy = .iso8601. See dates and times.
  • Undo: a stack of previous TodoList values is trivial because the list is a value type. Push a copy before each change and pop to undo.
  • Schema versions: add a version field to the saved JSON now, so that a future format can still read old files.
  • Real files: replace MemoryStorage with a file-based class. The main loop does not change by a single line; only the initial TodoApp(...) line does.
  • Concurrency: if several tasks could change the list, make TodoApp an actor. The bank project shows exactly that.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Why does the project make TodoList.items private(set)?

    private(set) keeps reading open and writing closed. All changes go through methods that enforce the rules, such as non-empty titles and unique numbers.
  2. 2. What is the main benefit of the Storage protocol?

    The repository depends on the protocol, not on a concrete place. Swapping the implementation changes one line in the main program.
  3. 3. Which statement about throws(TodoError) is true?

    Typed throws lists the single error type a function can produce, and the compiler enforces it.
  4. 4. Why does statistics() sort the tag counts before printing them?

    Swift randomizes the iteration order of dictionaries and sets per process. Sorting first gives deterministic output.
  5. 5. What happens with let list = TodoList() followed by list.add(...) on a mutating method?

    A let struct is entirely immutable. You must declare it with var to call mutating methods.

Summary

  • Separate a program into layers: model, persistence, command parsing, application logic and the console loop. Only the last one prints.
  • Structs with private(set) properties and mutating methods give a model that protects its own rules.
  • Codable synthesizes JSON encoding and decoding; use sortedKeys for stable output and map decoding errors to messages of your own.
  • A storage protocol hides where data lives, so memory, files and tests share the same code.
  • A Command enum and a throwing parse function turn unreliable text into reliable values before any logic runs.
  • Sort dictionaries before printing, and use typed throws to make every failure part of a function's visible contract.

Next: Project: Bank Account Simulation