0
0
Swiftprogramming~5 mins

Main entry point and @main attribute in Swift

Choose your learning style9 modes available
Introduction

The main entry point tells the program where to start running. The @main attribute marks the starting place in Swift.

When you want to define where your Swift program begins.
When creating a command-line tool or app without using storyboard.
When you want to customize the program's startup behavior.
When you want to use a custom type as the program's entry point.
Syntax
Swift
@main
struct MyApp {
    static func main() {
        // code to run first
    }
}

The @main attribute marks the type that provides the program's entry point.

The type must have a static main() method where the program starts.

Examples
This example prints a greeting when the program starts.
Swift
@main
struct HelloWorld {
    static func main() {
        print("Hello, world!")
    }
}
You can use a class instead of a struct with @main.
Swift
@main
class AppEntry {
    static func main() {
        print("Starting app...")
    }
}
An enum can also be the entry point with @main.
Swift
@main
enum Program {
    static func main() {
        print("Program started")
    }
}
Sample Program

This program starts by printing a welcome message using the @main attribute.

Swift
@main
struct SimpleApp {
    static func main() {
        print("Welcome to SimpleApp!")
    }
}
OutputSuccess
Important Notes

Only one type in your program can have the @main attribute.

The main() method must be static and have no parameters.

If you don't use @main, Swift looks for a top-level main.swift file or uses the default app lifecycle.

Summary

The @main attribute marks the program's starting point.

The type with @main must have a static main() method.

This lets you control what runs first in your Swift program.