0
0
Swiftprogramming~5 mins

Cancellation handling in Swift - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Cancellation handling
O(n)
Understanding Time Complexity

When we handle cancellation in Swift, we want to know how stopping a task early affects how long the program runs.

We ask: How does the program's work change when we cancel tasks?

Scenario Under Consideration

Analyze the time complexity of the following code snippet.


func performTask(with items: [Int], isCancelled: () -> Bool) {
    for item in items {
        if isCancelled() {
            break
        }
        // Simulate work
        print("Processing \(item)")
    }
}
    

This code processes a list of items but stops early if cancellation is detected.

Identify Repeating Operations

Identify the loops, recursion, array traversals that repeat.

  • Primary operation: Looping through the array items one by one.
  • How many times: Up to the number of items, but may stop earlier if cancelled.
How Execution Grows With Input

Execution grows with the number of items unless cancellation happens early.

Input Size (n)Approx. Operations
10Up to 10, or fewer if cancelled early
100Up to 100, or fewer if cancelled early
1000Up to 1000, or fewer if cancelled early

Pattern observation: The work grows linearly with input size but can be cut short by cancellation.

Final Time Complexity

Time Complexity: O(n)

This means the work grows in a straight line with the number of items, but may be less if we stop early.

Common Mistake

[X] Wrong: "Cancellation makes the code always run instantly or in constant time."

[OK] Correct: Cancellation only stops the work early sometimes; if not cancelled, the code still runs through all items.

Interview Connect

Understanding how cancellation affects time helps you explain real-world task management and responsiveness in apps.

Self-Check

"What if we changed the cancellation check to happen only every 10 items? How would the time complexity change?"