0
0
Swiftprogramming~5 mins

Why Swift for Apple and beyond - Performance Analysis

Choose your learning style9 modes available
Time Complexity: Why Swift for Apple and beyond
O(n)
Understanding Time Complexity

When we write programs in Swift, it is important to know how fast they run as we give them more work.

We want to understand how the time to finish changes when the input grows bigger.

Scenario Under Consideration

Analyze the time complexity of the following code snippet.


func printNumbers(_ n: Int) {
    for i in 1...n {
        print(i)
    }
}

printNumbers(5)
    

This code prints numbers from 1 up to n. It shows how the work grows as n grows.

Identify Repeating Operations

Identify the loops, recursion, array traversals that repeat.

  • Primary operation: The for-loop that prints each number.
  • How many times: It runs exactly n times, once for each number.
How Execution Grows With Input

Explain the growth pattern intuitively.

Input Size (n)Approx. Operations
1010 prints
100100 prints
10001000 prints

Pattern observation: When n doubles, the work doubles too. The time grows in a straight line with n.

Final Time Complexity

Time Complexity: O(n)

This means the time to finish grows directly with the size of the input.

Common Mistake

[X] Wrong: "The loop runs a fixed number of times no matter what."

[OK] Correct: The loop runs as many times as the input number n, so bigger n means more work.

Interview Connect

Understanding how loops affect time helps you explain your code clearly and shows you know how programs scale.

Self-Check

"What if we added a nested loop inside the first loop? How would the time complexity change?"