Hands-On Lab: Build a Todo Engine with Codable, Filtering, Sorting and Persistence
What We Will Build
A todo engine with priorities, filtering, sorting, summary counts, and saving to a JSON file. The user interface is not needed, so you can later connect it to SwiftUI.
Step 1: Models
swift
import Foundation
enum Priority: Int, Codable, Comparable, CaseIterable {
case low = 1, medium, high
static func < (a: Priority, b: Priority) -> Bool { a.rawValue < b.rawValue }
}
struct Todo: Codable, Identifiable {
let id: Int
var title: String
var priority: Priority
var done = false
}
let t = Todo(id: 1, title: "Write", priority: .high)
let enc = JSONEncoder(); enc.outputFormatting = [.sortedKeys]
print(String(decoding: try enc.encode(t), as: UTF8.self))
Output
{"done":false,"id":1,"priority":3,"title":"Write"}
Step 2: Engine, Filter and Sort
swift
import Foundation
enum Priority: Int, Codable, Comparable, CaseIterable {
case low = 1, medium, high
static func < (a: Priority, b: Priority) -> Bool { a.rawValue < b.rawValue }
}
struct Todo: Codable, Identifiable {
let id: Int
var title: String
var priority: Priority
var done = false
}
struct TodoStore {
private(set) var todos: [Todo] = []
private var nextID = 1
mutating func add(_ title: String, _ p: Priority) {
todos.append(Todo(id: nextID, title: title, priority: p)); nextID += 1
}
mutating func complete(_ id: Int) {
if let i = todos.firstIndex(where: { $0.id == id }) { todos[i].done = true }
}
var pending: [Todo] {
todos.filter { !$0.done }.sorted { ($0.priority, $1.title) > ($1.priority, $0.title) }
}
var countByPriority: [Priority: Int] {
Dictionary(grouping: todos, by: \.priority).mapValues(\.count)
}
}
var store = TodoStore()
store.add("Pay bills", .high)
store.add("Read book", .low)
store.add("Call mom", .high)
store.add("Plan trip", .medium)
store.complete(1)
print(store.pending.map(\.title))
let counts = store.countByPriority
print(Priority.allCases.map { "\($0): \(counts[$0] ?? 0)" })
Output
["Call mom", "Plan trip", "Read book"] | ["low: 1", "medium: 1", "high: 2"]
Step 3: Save and Load
swift
import Foundation
struct Todo: Codable { let id: Int; var title: String; var done: Bool }
let items = [Todo(id: 1, title: "A", done: true), Todo(id: 2, title: "B", done: false)]
let url = FileManager.default.temporaryDirectory.appendingPathComponent("todos-lab.json")
try JSONEncoder().encode(items).write(to: url)
let loaded = try JSONDecoder().decode([Todo].self, from: Data(contentsOf: url))
print(loaded.map(\.title), loaded.filter(\.done).count)
try FileManager.default.removeItem(at: url)
Output
["A", "B"] 1
Challenges
- Add
dueDateand sort by it - Search todos by words in the title
- Handle a missing or corrupted file with a safe fallback
- Show the engine in a SwiftUI list
Conclusion
Codable, enums and collection functions handle the full data flow of an app.
Quick Summary: Codable models; filter/sort/group; JSON persistence.

