Explain it simply
Project: Task Manager App - Part 3 (Polish + Wrap Up), in plain language
Part 3 is the final stage of this project. We'll define a custom Error enum called TaskError and write throws functions to gracefully handle misuse cases like an empty title or trying to complete a non-existent id. We'll turn addTask into a throwing function with validation and use do-catch on the caller side. Finally, we'll add a printSummary() method that groups done/pending counts by priority and outputs a report format. By the end of this stage, you'll have finished a project that combines error handling, closures, structs/classes, and enums all together.
Problem → Why → Solution
The problem — why this concept matters
Not understanding why calling a throws function without try causes a compile error
A common mistake
Putting a general catch { } at the top of your catch blocks instead of checking specific cases first, so the specific catch code never runs
Core concept — understand how it works
Build Project: Task Manager App - Part 3 (Polish + Wrap Up) in vertical slices that separate UI, domain state, persistence or services, and tests. Cover normal, boundary, nil, error, cancellation, and concurrency paths without blocking main-actor work.
- project requirements
- components, state, and services
- tested UI
Explain the type, ownership, and runtime behavior of Project: Task Manager App - Part 3 (Polish + Wrap Up)
Core syntax or pattern
enum TaskError: Error {
case emptyTitle
case taskNotFound(id: Int)
}
extension TaskManager {
func addTask(title: String, priority: Priority) throws {
guard !title.trimmingCharacters(in: .whitespaces).isEmpty else {
throw TaskError.emptyTitle
}
let newTask = Task(id: tasks.count + 1, title: title, priority: priority)
tasks.append(newTask)
}
func completeTask(id: Int) throws {
guard let index = tasks.firstIndex(where: { $0.id == id }) else {
throw TaskError.taskNotFound(id: id)
}
tasks[index].isDone = true
}
func printSummary() {
print("===== Summary =====")
print("Total: \(tasks.count), Done: \(tasks.count - pendingCount), Pending: \(pendingCount)")
for p in [Priority.high, .medium, .low] {
let count = tasks.filter { $0.priority == p && !$0.isDone }.count
print("\(p.rawValue) pending: \(count)")
}
}
}
do {
try manager.addTask(title: "Practice error handling", priority: .high)
try manager.completeTask(id: 99)
} catch TaskError.emptyTitle {
print("A task cannot be added with an empty title")
} catch TaskError.taskNotFound(let id) {
print("Task id #\(id) was not found")
} catch {
print("Unknown error: \(error)")
}
manager.printSummary()Build Project: Task Manager App - Part 3 (Polish + Wrap Up) in vertical slices that separate UI, domain state, persistence or services, and tests. Cover normal, boundary, nil, error, cancellation, and concurrency paths without blocking main-actor work.
Read the code step by step
- project requirements
enum TaskError: Error {Part 3 is the final stage of this project. We'll define a custom Error enum called TaskError and write throws functions to gracefully handle misuse cases like an empty title or trying to complete a non-existent id. We'll turn addTask into a throwing function with validation and use do-catch on the caller side. Finally, we'll add a printSummary() method that groups done/pending counts by priority and outputs a report format. By the end of this stage, you'll have finished a project that combines error handling, closures, structs/classes, and enums all together.
- components, state, and services
print("===== Summary =====")Build Project: Task Manager App - Part 3 (Polish + Wrap Up) in vertical slices that separate UI, domain state, persistence or services, and tests. Cover normal, boundary, nil, error, cancellation, and concurrency paths without blocking main-actor work.
- tested UI
manager.printSummary()Run and test an original Project: Task Manager App - Part 3 (Polish + Wrap Up) example with empty, nil, boundary, invalid, error, and cancellation cases. Verify value copying, shared references, actor isolation, and main-actor effects where relevant.
- project requirements
- components, state, and services
- tested UI
Success
Explain the type, ownership, and runtime behavior of Project: Task Manager App - Part 3 (Polish + Wrap Up)
Failure
Not understanding why calling a throws function without try causes a compile error
Let's think about this for a second
Part 3 is the final stage of this project. We'll define a custom Error enum called TaskError and write throws functions to gracefully handle misuse cases like an empty title or trying to complete a non-existent id. We'll turn addTask into a throwing function with validation and use do-catch on the caller side. Finally, we'll add a printSummary() method that groups done/pending counts by priority and outputs a report format. By the end of this stage, you'll have finished a project that combines error handling, closures, structs/classes, and enums all together.
Let's build it
Define a TaskError enum with two cases, emptyTitle and taskNotFound(id: Int), conforming to the Error protocol. Turn addTask(title:priority:) into a throws function that throws TaskError.emptyTitle if title.isEmpty. Turn completeTask(id:) into throws too, throwing TaskError.taskNotFound if no matching task is found. Write a printSummary() method that prints total, done, and pending counts along with the pending count for each priority. In your main code, use a do-catch block to handle both error cases and print a user-friendly error message.
Sample Code
enum TaskError: Error {
case emptyTitle
case taskNotFound(id: Int)
}
extension TaskManager {
func addTask(title: String, priority: Priority) throws {
guard !title.trimmingCharacters(in: .whitespaces).isEmpty else {
throw TaskError.emptyTitle
}
let newTask = Task(id: tasks.count + 1, title: title, priority: priority)
tasks.append(newTask)
}
func completeTask(id: Int) throws {
guard let index = tasks.firstIndex(where: { $0.id == id }) else {
throw TaskError.taskNotFound(id: id)
}
tasks[index].isDone = true
}
func printSummary() {
print("===== Summary =====")
print("Total: \(tasks.count), Done: \(tasks.count - pendingCount), Pending: \(pendingCount)")
for p in [Priority.high, .medium, .low] {
let count = tasks.filter { $0.priority == p && !$0.isDone }.count
print("\(p.rawValue) pending: \(count)")
}
}
}
do {
try manager.addTask(title: "Practice error handling", priority: .high)
try manager.completeTask(id: 99)
} catch TaskError.emptyTitle {
print("A task cannot be added with an empty title")
} catch TaskError.taskNotFound(let id) {
print("Task id #\(id) was not found")
} catch {
print("Unknown error: \(error)")
}
manager.printSummary()Since id #99 can't be found, the message "Task id #99 was not found" gets printed, and printSummary() outputs a report with pending counts broken down by priority.Give it 5 minutes
Add a duplicateTitle case to TaskError, and write the logic yourself so addTask throws an error if a task with the same title already exists. Spend about 5 minutes on it.
One thing to watch out for
Order matters when writing catch blocks — always keep the general catch { } last, otherwise specific error cases may never be reached, and it can even cause a compile error.
Real-world usage
How to apply it in a real project
Run and test an original Project: Task Manager App - Part 3 (Polish + Wrap Up) example with empty, nil, boundary, invalid, error, and cancellation cases. Verify value copying, shared references, actor isolation, and main-actor effects where relevant.
Mini challenge
Build it yourself
Run and test an original Project: Task Manager App - Part 3 (Polish + Wrap Up) example with empty, nil, boundary, invalid, error, and cancellation cases. Verify value copying, shared references, actor isolation, and main-actor effects where relevant.
- Rebuild the example without copying it
- Test a normal input and an edge case
- Predict the compiler or output result before running it
enum TaskError: Error {
case emptyTitle
case taskNotFound(id: Int)
}
extension TaskManager {
func addTask(title: String, priority: Priority) throws {
guard !title.trimmingCharacters(in: .whitespaces).isEmpty else {
throw TaskError.emptyTitle
}
let newTask = Task(id: tasks.count + 1, title: title, priority: priority)
tasks.append(newTask)
}
func completeTask(id: Int) throws {
guard let index = tasks.firstIndex(where: { $0.id == id }) else {
throw TaskError.taskNotFound(id: id)
}
tasks[index].isDone = true
}
func printSummary() {
print("===== Summary =====")
print("Total: \(tasks.count), Done: \(tasks.count - pendingCount), Pending: \(pendingCount)")
for p in [Priority.high, .medium, .low] {
let count = tasks.filter { $0.priority == p && !$0.isDone }.count
print("\(p.rawValue) pending: \(count)")
}
}
}
do {
try manager.addTask(title: "Practice error handling", priority: .high)
try manager.completeTask(id: 99)
} catch TaskError.emptyTitle {
print("A task cannot be added with an empty title")
} catch TaskError.taskNotFound(let id) {
print("Task id #\(id) was not found")
} catch {
print("Unknown error: \(error)")
}
manager.printSummary()Expected: Explain the type, ownership, and runtime behavior of Project: Task Manager App - Part 3 (Polish + Wrap Up)
Show hint
Run and test an original Project: Task Manager App - Part 3 (Polish + Wrap Up) example with empty, nil, boundary, invalid, error, and cancellation cases. Verify value copying, shared references, actor isolation, and main-actor effects where relevant.
Quick quiz 1 / 3
Quick quiz 2 / 3
Quick quiz 3 / 3
What to remember
- project requirements → components, state, and services → tested UI
- Build Project: Task Manager App - Part 3 (Polish + Wrap Up) in vertical slices that separate UI, domain state, persistence or services, and tests. Cover normal, boundary, nil, error, cancellation, and concurrency paths without blocking main-actor work.
- Not understanding why calling a throws function without try causes a compile error
- Run and test an original Project: Task Manager App - Part 3 (Polish + Wrap Up) example with empty, nil, boundary, invalid, error, and cancellation cases. Verify value copying, shared references, actor isolation, and main-actor effects where relevant.
The Swift Programming Language — Swift.org