Adding the @UIApplicationMain
attribute to a class
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate { ... }
is equivalent to calling UIApplicationMain()
in "main.swift"
with "AppDelegate" as the name of the class from which the application delegate is instantiated:
UIApplicationMain(
CommandLine.argc,
UnsafeMutableRawPointer(CommandLine.unsafeArgv)
.bindMemory(
to: UnsafeMutablePointer<Int8>.self,
capacity: Int(CommandLine.argc)),
nil,
NSStringFromClass(AppDelegate.self)
)
(compare e.g. What does "@UIApplicationMain" mean? and Subclass UIApplication with Swift).
With either method, an instance of the AppDelegate
class is created
and passed as delegate to the application object. So yes,
let appDelegate = UIApplication.shared.delegate as! AppDelegate
is safe.
But note that there is nothing special about the class name "AppDelegate", this is just convention. You can define the application
delegate as
@UIApplicationMain
class MyFantasticAppDelegate: UIResponder, UIApplicationDelegate { ... }
in which case it of course would be
let appDelegate = UIApplication.shared.delegate as! MyFantasticAppDelegate
So the precise statement would be
Casting UIApplication.shared.delegate
to the type of the class defined as application delegate cannot fail.
By convention, that type is AppDelegate
, but it doesn't have to be.