0
0
Swiftprogramming~10 mins

Main entry point and @main attribute in Swift - Step-by-Step Execution

Choose your learning style9 modes available
Concept Flow - Main entry point and @main attribute
Program Start
@main Struct or Class
Call static main()
Execute main() code
Program Ends
Swift looks for a type marked with @main and calls its static main() method to start the program.
Execution Sample
Swift
import Foundation

@main
struct MyApp {
    static func main() {
        print("Hello, Swift!")
    }
}
This program uses @main on MyApp struct; Swift calls MyApp.main() to print a greeting.
Execution Table
StepActionEvaluationResult
1Program startsFind @main typeMyApp struct found
2Call MyApp.main()Execute main() methodPrints "Hello, Swift!"
3main() completesNo more codeProgram ends
💡 Program ends after main() finishes execution
Variable Tracker
VariableStartAfter Step 2Final
Output"""Hello, Swift!\n""Hello, Swift!\n"
Key Moments - 3 Insights
Why does Swift look for a static main() method inside the @main type?
Because the @main attribute tells Swift this is the program's entry point, so it calls the static main() method to start execution (see execution_table step 2).
Can we have multiple @main types in one Swift program?
No, only one @main type is allowed because Swift needs a single entry point to start the program (execution_table step 1).
What happens if main() does not exist inside the @main type?
The program will not compile because Swift requires a static main() method in the @main type to know where to start (refer to concept_flow).
Visual Quiz - 3 Questions
Test your understanding
Look at the execution table, what is printed during step 2?
A"Program starts"
B"Hello, Swift!"
C"MyApp struct found"
D"Program ends"
💡 Hint
Check the 'Result' column in execution_table row for step 2.
At which step does the program find the @main type?
AStep 3
BStep 2
CStep 1
DProgram never finds it
💡 Hint
Look at the 'Action' and 'Evaluation' columns in execution_table step 1.
If the static main() method was missing, what would happen?
ACompilation error occurs
BProgram prints nothing but runs
CProgram runs normally
DProgram ends immediately
💡 Hint
Refer to key_moments about missing main() method.
Concept Snapshot
@main attribute marks the program's entry point.
Swift calls the static main() method inside the @main type.
Only one @main type allowed per program.
main() contains code that runs first.
Program ends when main() finishes.
Full Transcript
In Swift, the program starts by looking for a type marked with @main. This attribute tells Swift where the program's entry point is. Swift then calls the static main() method inside that type. The main() method contains the code that runs first. For example, if main() prints "Hello, Swift!", that message appears when the program runs. The program ends when main() finishes. Only one @main type is allowed, and it must have a static main() method. If main() is missing, the program will not compile.