0
0
Swiftprogramming~5 mins

Main entry point and @main attribute in Swift - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Main entry point and @main attribute
O(n)
Understanding Time Complexity

When we look at the main entry point in Swift, we want to understand how the program starts and how the time it takes grows as the program runs.

We ask: How does the program's starting code affect the total work done as input size changes?

Scenario Under Consideration

Analyze the time complexity of the following code snippet.


    @main
    struct MyApp {
      static func main() {
        let n = 10
        for i in 1...n {
          print(i)
        }
      }
    }
    

This code defines the program's main entry point using the @main attribute and prints numbers from 1 to n.

Identify Repeating Operations

Identify the loops, recursion, array traversals that repeat.

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

As n grows, the number of print operations grows the same way.

Input Size (n)Approx. Operations
1010 print calls
100100 print calls
10001000 print calls

Pattern observation: The work grows directly with n; doubling n doubles the work.

Final Time Complexity

Time Complexity: O(n)

This means the time to run the main function grows in a straight line as the input size n increases.

Common Mistake

[X] Wrong: "The @main attribute itself makes the program run slower as n grows."

[OK] Correct: The @main attribute just marks where the program starts; it does not add extra work. The time depends on what the main function does, not the attribute.

Interview Connect

Understanding how the main entry point works and how its code scales helps you explain program startup and performance clearly in interviews.

Self-Check

"What if we replaced the for-loop with a recursive function that prints numbers from 1 to n? How would the time complexity change?"