Home What is @main in Swift
Post
Cancel

What is @main in Swift

In all programs you always have an entry point, a place where your app should start from, and swift is not an exception to that. If you remember the very old days we where having main.m as below:

1
2
3
4
5
6
7
main.m
int main(int argc, char *argv[])
{
    @autoreleasepool {
    return UIApplicationMain(argc, argv, nil, NSStringFromClass([AppDelegate class]));
    }
}

The code above is a very old code that we don’t use anymore, it’s the old way in the time of objective c to tell the entry point of the app. In swift you can still use main.swift and it will be the entry point for your app.

1
2
3
4
main.swift
autoreleasepool {
  UIApplicationMain(CommandLine.argc, CommandLine.unsafeArgv, nil, NSStringFromClass(AppDelegate.self))
}

Now these days we have two things:

@UIApplicationMain

Adding this annotation to a class means that this class is the application delegate and it’s same as you are creating the UIApplicationMain(:,:,:,:) yourself and supplying this class as the delegate.

@Main

Adding this annotation to a class, struct, or enum means that it contain the entry point for the app and it should provide a static main function. So you can do something like this:

1
2
3
4
5
6
@main
class MyApp {
  static func main() {
    UIApplicationMain(CommandLine.argc, CommandLine.unsafeArgv, nil, NSStringFromClass(AppDelegate.self))
  }
}

And this will be the entry point for your app, but remember to remove @UIApplicationMain from your app delegate to make it work.

SwiftUI App protocol

The new @main used on a class or struct confirmed to App class to give entry point for your SwiftUI app, and the App will take care of creating all the needed things to start your SwiftUI app so you don’t need to do any extra things or handle things by your self including the platform specific code.

1
2
3
4
5
6
7
8
@main
struct MyApp: App { // App is handling the `main` function
  var body: some Scene {
    WindowGroup {
      SplashView()
    }
  }
}

-❤️~.
If you have any questions you can send me a message on Twitter or facebook. Also you can check my Github page or my Apps.

This post is licensed under CC BY 4.0 by the author.