Main entry point and @main attribute in Swift - Time & Space 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?
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 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.
As n grows, the number of print operations grows the same way.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 print calls |
| 100 | 100 print calls |
| 1000 | 1000 print calls |
Pattern observation: The work grows directly with n; doubling n doubles the work.
Time Complexity: O(n)
This means the time to run the main function grows in a straight line as the input size n increases.
[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.
Understanding how the main entry point works and how its code scales helps you explain program startup and performance clearly in interviews.
"What if we replaced the for-loop with a recursive function that prints numbers from 1 to n? How would the time complexity change?"