The entry point in a plain Swift module is the file in the module called main.swift
. main.swift
is the only file which is allowed to have expressions and statements at the top level (all other Swift files in the module can only contain declarations).
Cocoa Touch uses the @UIApplicationMain
attribute on an implementation of UIApplicationDelegate
instead of a main.swift
file to mark the entry point. Cocoa used to use a minimal main.swift
file which simply called NSApplicationMain
, but as of Xcode 6.1 uses the @NSApplicationMain
attribute on an implementation of NSApplicationDelegate
.
In the AppDelegate.swift
file you can see @UIApplicationMain
.
The AppDelegate is the initial entry file.
Basically: main.m
and AppDelegate.m
are kinda merged in Swift
to just AppDelegate.swift
You may want to read Files and Initialization
The exception is a special file named “main.swift”, which behaves much like a playground file, but is built with your app’s source code. The “main.swift” file can contain top-level code, and the order-dependent rules apply as well. In effect, the first line of code to run in “main.swift” is implicitly defined as the main entrypoint for the program. This allows the minimal Swift program to be a single line — as long as that line is in “main.swift”.
In Xcode, Mac templates default to including a “main.swift” file, but for iOS apps the default for new iOS project templates is to add @UIApplicationMain to a regular Swift file. This causes the compiler to synthesize a main entry point for your iOS app, and eliminates the need for a “main.swift” file.
Alternatively, you can link in an implementation of main written in Objective-C, common when incrementally migrating projects from Objective-C to Swift.
In Swift 5.3 there is a new @main
attribute which lets you control where your entry point is in your project rather than just main.swift
. There can only be one main entry and you can't have a main.swift
file and a an attribute @main
. See https://github.com/apple/swift-evolution/blob/master/proposals/0281-main-attribute.md for more details.
@main
struct App {
static func main() {
print("Starting.")
}
}
In Swift apps there are attributes:
@UIApplicationMain
(Cocoa Touch)@NSApplicationMain
(Cocoa)that tell the swift compiler where is the entry point of the application.
What swift compiler does under the hood is that it creates a main
function, which basically looks the same as in Objective-C apps and treats this method as the app's entry point (a first method that is called when the application process is started).
If you want to read more about what swift compiler does with Main
attributes, how the OS knows where is the entry point of the application, I encourage you to read this article: Understanding iOS app entry point
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With