Thuta Learning
Swift
ProjectsProgrammingBeginner

Project: Task Manager App - Part 2 (Adding the Main Feature)

SwiftLesson 3130 min

What you'll walk away with

  • Explain the type, ownership, and runtime behavior of Project: Task Manager App - Part 2 (Adding the Main Feature)
  • Test nil, error, boundary, and concurrency cases
  • Write safe and testable Swift

Explain it simply

Project: Task Manager App - Part 2 (Adding the Main Feature), in plain language

In this part, we'll add the core features — task completion, filtering, sorting — to the TaskManager we built in Part 1. We'll write a method that accepts a closure as a parameter and filters the task list by a custom condition, which is practice for the higher-order function pattern. We'll use sorted(by:) with a custom comparator closure to sort by priority. We'll write the pending task count as a computed property so it needs no get/set logic, reinforcing the properties topic. By the end of this stage, the app becomes a tool that does practical operations, not just holds data.

Problem → Why → Solution

The problem — why this concept matters

Writing long manual filter loops with for instead of using closure-based filter/sorted on the tasks array

A common mistake

In completeTask(id:), force-unwrapping the result of firstIndex(where:) instead of optional binding, causing crashes

Core concept — understand how it works

Build Project: Task Manager App - Part 2 (Adding the Main Feature) 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.

Mental model
  1. project requirements
  2. components, state, and services
  3. tested UI

Explain the type, ownership, and runtime behavior of Project: Task Manager App - Part 2 (Adding the Main Feature)

Core syntax or pattern

swift
extension TaskManager {
    func completeTask(id: Int) {
        if let index = tasks.firstIndex(where: { $0.id == id }) {
            tasks[index].isDone = true
        }
    }

    func filter(by condition: (Task) -> Bool) -> [Task] {
        return tasks.filter(condition)
    }

    func tasksSortedByPriority() -> [Task] {
        let order: [Priority] = [.high, .medium, .low]
        return tasks.sorted {
            order.firstIndex(of: $0.priority)! < order.firstIndex(of: $1.priority)!
        }
    }

    var pendingCount: Int {
        return tasks.filter { !$0.isDone }.count
    }
}

manager.completeTask(id: 1)
let highPriorityTasks = manager.filter { $0.priority == .high }
print("High priority pending: \(highPriorityTasks.count)")
print("Total pending: \(manager.pendingCount)")

Build Project: Task Manager App - Part 2 (Adding the Main Feature) 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

  1. project requirementsextension TaskManager {

    In this part, we'll add the core features — task completion, filtering, sorting — to the TaskManager we built in Part 1. We'll write a method that accepts a closure as a parameter and filters the task list by a custom condition, which is practice for the higher-order function pattern. We'll use sorted(by:) with a custom comparator closure to sort by priority. We'll write the pending task count as a computed property so it needs no get/set logic, reinforcing the properties topic. By the end of this stage, the app becomes a tool that does practical operations, not just holds data.

  2. components, state, and servicesreturn tasks.sorted {

    Build Project: Task Manager App - Part 2 (Adding the Main Feature) 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.

  3. tested UIprint("Total pending: \(manager.pendingCount)")

    Run and test an original Project: Task Manager App - Part 2 (Adding the Main Feature) example with empty, nil, boundary, invalid, error, and cancellation cases. Verify value copying, shared references, actor isolation, and main-actor effects where relevant.

Execution flow
  1. project requirements
  2. components, state, and services
  3. tested UI

Success

Explain the type, ownership, and runtime behavior of Project: Task Manager App - Part 2 (Adding the Main Feature)

Failure

Writing long manual filter loops with for instead of using closure-based filter/sorted on the tasks array

Let's think about this for a second

In this part, we'll add the core features — task completion, filtering, sorting — to the TaskManager we built in Part 1. We'll write a method that accepts a closure as a parameter and filters the task list by a custom condition, which is practice for the higher-order function pattern. We'll use sorted(by:) with a custom comparator closure to sort by priority. We'll write the pending task count as a computed property so it needs no get/set logic, reinforcing the properties topic. By the end of this stage, the app becomes a tool that does practical operations, not just holds data.

Let's build it

Write a completeTask(id: Int) method that sets isDone to true on the task with the matching id (find the array index with firstIndex(where:)). Write a filter(by condition: (Task) -> Bool) -> [Task] method that filters the task array using a closure condition. Write a tasks(sortedBy:) method that returns the array sorted from high to low priority. Add a var pendingCount: Int computed property that returns the count of tasks where isDone == false. Update printAllTasks() to print in sortedBy priority order.

Sample Code

swift
extension TaskManager {
    func completeTask(id: Int) {
        if let index = tasks.firstIndex(where: { $0.id == id }) {
            tasks[index].isDone = true
        }
    }

    func filter(by condition: (Task) -> Bool) -> [Task] {
        return tasks.filter(condition)
    }

    func tasksSortedByPriority() -> [Task] {
        let order: [Priority] = [.high, .medium, .low]
        return tasks.sorted {
            order.firstIndex(of: $0.priority)! < order.firstIndex(of: $1.priority)!
        }
    }

    var pendingCount: Int {
        return tasks.filter { !$0.isDone }.count
    }
}

manager.completeTask(id: 1)
let highPriorityTasks = manager.filter { $0.priority == .high }
print("High priority pending: \(highPriorityTasks.count)")
print("Total pending: \(manager.pendingCount)")
You should see
After calling completeTask, pendingCount drops by one, and the high-priority filter result also prints the correct array.

Give it 5 minutes

Write a line yourself that filters out only the tasks where isDone == true, and add a computed property called completedCount. Spend about 5 minutes on it.

One thing to watch out for

Since array elements are the Task value type, you need to mutate them directly by index, like tasks[index].isDone = true — changing the local copy inside a for task in tasks loop won't change the original array.

Real-world usage

How to apply it in a real project

Run and test an original Project: Task Manager App - Part 2 (Adding the Main Feature) 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 2 (Adding the Main Feature) 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
swift
extension TaskManager {
    func completeTask(id: Int) {
        if let index = tasks.firstIndex(where: { $0.id == id }) {
            tasks[index].isDone = true
        }
    }

    func filter(by condition: (Task) -> Bool) -> [Task] {
        return tasks.filter(condition)
    }

    func tasksSortedByPriority() -> [Task] {
        let order: [Priority] = [.high, .medium, .low]
        return tasks.sorted {
            order.firstIndex(of: $0.priority)! < order.firstIndex(of: $1.priority)!
        }
    }

    var pendingCount: Int {
        return tasks.filter { !$0.isDone }.count
    }
}

manager.completeTask(id: 1)
let highPriorityTasks = manager.filter { $0.priority == .high }
print("High priority pending: \(highPriorityTasks.count)")
print("Total pending: \(manager.pendingCount)")

Expected: Explain the type, ownership, and runtime behavior of Project: Task Manager App - Part 2 (Adding the Main Feature)

Show hint

Run and test an original Project: Task Manager App - Part 2 (Adding the Main Feature) 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

What best describes the core idea of Project: Task Manager App - Part 2 (Adding the Main Feature)?

Quick quiz 2 / 3

Which mistake should you avoid first?

Quick quiz 3 / 3

How should this be applied in a real project?

What to remember

  • project requirements → components, state, and services → tested UI
  • Build Project: Task Manager App - Part 2 (Adding the Main Feature) 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.
  • Writing long manual filter loops with for instead of using closure-based filter/sorted on the tasks array
  • Run and test an original Project: Task Manager App - Part 2 (Adding the Main Feature) 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

Easy traps

  • Writing long manual filter loops with for instead of using closure-based filter/sorted on the tasks array
  • In completeTask(id:), force-unwrapping the result of firstIndex(where:) instead of optional binding, causing crashes
  • Assuming one sample output proves nil, ownership, actor isolation, and every error path.

Hands-on Exercise

Run and test an original Project: Task Manager App - Part 2 (Adding the Main Feature) example with empty, nil, boundary, invalid, error, and cancellation cases. Verify value copying, shared references, actor isolation, and main-actor effects where relevant.

You'll know it worked when: After calling completeTask, pendingCount drops by one, and the high-priority filter result also prints the correct array.

Updated on

Progress is saved only in this browser on this device. It isn't synced to other devices.

Report a problem with this lessonOpens your email app with this lesson's address filled in — nothing is sent until you send it.

Project: Task Manager App - Part 2 (Adding the Main Feature) | Thuta Learning