There is no main()
method in swift. The program must start the execution from somewhere. So what is the entry point of swift code execution and how is it decided?
问题:
回答1:
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
.
回答2:
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
回答3:
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.