Entry Points in Swift: How @main and @UIApplicationMain work internally

Entry Points in Swift: How @main and @UIApplicationMain work internally

In this article, we'll see how Swift determines the entry point of an app, the different attributes used to alter this behavior in iOS, how they work internally, and what Swift 5.3's new @main attribute brings to the table.

How Swift Scripts Work

When executing Swift code from the command line, by default, the code will be read from top to bottom just like any other scripting language. While Swift scripts support everything you'd have in any other context, they have the additional advantage of being able to write expressions in a global scope:

print("Hello")

struct MyStruct {
    func foo() {}
}

MyStruct().foo()

In an iOS app, by default, doing so would result in the Expressions are not allowed at the top level error, but in a scripted world where you want to execute something as possible, there's no point in preventing this behavior.

Deep down, the ability to call code globally is just a cool syntax sugar. What is really happening is that Swift is abstracting your global code inside a fake main C function:

func main(argc: Int32, argv: UnsafeMutablePointer<UnsafeMutablePointer<Int8>?>) -> Int32 {
    print("Hello")

    struct MyStruct {
        func foo() {}
    }

    MyStruct().foo()
}

Swift uses clang internally to compile and provide interoperability with C/C++/Objective-C, so it's natural that the starting point of a script/app mimicks it as well. You can check this with swiftc (file) -emit-sil, which will print Swift's Intermediate Language representation of your code after optimizing and generating any additional code it needs. In this case, we'll see a definition for a main function and our script's contents inside of it.

sil @main
// a bunch of stuff that defines your top-level code!

Interestingly enough, it's not possible for you to "steal" and define your own main function in that context. The generated main function is literally symbolized as main, while anything you define will internally have its symbol mangled (an unique identifier for your function or class, based on the context where it was defined), like s4MyApp4mainCACycfc.

This is what happens when your Swift script/binary only contains one file, but what if it contains multiple files?

In this case, as we can't have multiple starting points, we must designate one of them as the main one. Like before, the main file will be the entry point of the app and gain access to global expressions, but now, as expected, any additional file will have to follow your usual Swift rules. In Swift, designating the main file is just a matter of naming it main.swift.

swiftc main.swift anotherFile.swift

@UIApplicationMain -- When the entry point needs to be controlled

But not all kinds of programs fit into this top-bottom code execution format -- for example, in iOS, the execution of the app relies on running and maintaining an UIApplication instance, a process that is the same for every single iOS app. This initial process of booting an UIApplication is abstracted by UIKit, and there's no reason for you as an user to have to worry about it, specially considering that this is the very first thing your app should do. For this reason, you could argue that handling this responsability to the user could even have negative consequences. Imagine accidentally shipping a version where your app doesn't boot at all!

To prevent this issue from happening, Apple thought that if UIKit is responsible for providing the code necessary to boot an iOS app, then it should probably get its hands dirty and do it itself. The Swift compiler then started supporting two new special attributes: @UIApplicationMain and @NSApplicationMain (for macOS).

These attributes are magical, but they don't deviate from what we already know. Their purpose is to automatically generate an entry point, and internally, what happens is that the presence of these attributes will result in a fake main function being added to your binary:

func main(argc: Int32, argv: UnsafeMutablePointer<UnsafeMutablePointer<Int8>?>) -> Int32 {
    return UIApplicationMain(argc, argv, nil, ClassName)
}

The content of the function depends on the attribute you used, but as you can expect, it simply initializes your iOS app.

You might know UIApplicationMain() if you ever needed to use a subclass of an UIApplication in your app -- this is the function that bootstraps an iOS app, and you can use the third and fourth arguments to change the classes you want to use as your UIApplication and UIApplicationDelegate. This means that there's nothing special about the @UIApplicationMain attribute, and you can reproduce what the compiler is doing by removing it and creating your own main.swift file. This is a legit technique to fine-tune the initialization of your app, which you can use to run code before your app launches (literally).

UIHooks.swizzleEverything()
UIApplicationMain(CommandLine.argc, CommandLine.unsafeArgv, nil, "AppDelegate")

As a fake main function is emitted as a result of using the @UIApplicationMain attribute, you can't have both the attribute and a main.swift file. Trying to use both will result in a duplicated symbol error, and in some situations the compiler will even give you a specific attribute cannot be used in a module that contains top-level code error.

Swift 5.3 and @main

Many years later, it was realized that UIKit was not the only framework that benefitted from controlling the entry point. Many frameworks for Swift CLI tools involve some sort of initial setup, and so it would be great if the language provided a standard way to replicating what was currently hardcoded as @UIApplicationMain. Finally, in Swift 5.3, the @main attribute was added to allow developers to control this behavior.

@main struct MyScript {
    static func main() throws {
    	print("SwiftRocks!")
    }
}

@main works similarly to a protocol -- when added, you must define a main() method that will serve as the entry point for your Swift code. Apart from that, @main works precisely like @UIApplicationMain. The fake main function is still emitted, but instead of returning the hardcoded UIKit behavior, it executes the function that you defined as a result of adding the attribute to a type. As seen in WWDC 2020, the new @main attribute is used by SwiftUI and the new Widgets extension to abstract the definition of their entry points.

One particularly interesting use of it is in Apple's swift-argument-parser library, which is a tool for creating commands and arguments for CLI tools. Before Swift 5.3, you had to manually initialize your tool by calling its main command's main() method from the library, but now, you can simply attach the new attribute to mark it as the starting point.

Before:

struct Repeat: ParsableCommand {
    @Argument(help: "The phrase to repeat.")
    var phrase: String

    mutating func run() throws {
        for _ in 1...5 {
            print(phrase)
        }
    }
}

Repeat.main()

Post Swift 5.3:

@main struct Repeat: ParsableCommand {
    @Argument(help: "The phrase to repeat.")
    var phrase: String

    mutating func run() throws {
        for _ in 1...5 {
            print(phrase)
        }
    }
}

Because of this addition, using @UIApplicationMain is now officially deprecated as Apple allows you to use the new @main attribute in your AppDelegates (except in the second Xcode 12 beta, where the feature was temporarily disabled).