将@UIApplicationMain 属性添加到类中
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate { ... }
相当于在“main.swift”中调用UIApplicationMain()
使用“AppDelegate”作为实例化应用程序委托的类的名称:
UIApplicationMain(
CommandLine.argc,
UnsafeMutableRawPointer(CommandLine.unsafeArgv)
.bindMemory(
to: UnsafeMutablePointer<Int8>.self,
capacity: Int(CommandLine.argc)),
nil,
NSStringFromClass(AppDelegate.self)
)
(比较例如What does "@UIApplicationMain" mean?和Subclass UIApplication with Swift)。
使用任一方法,都会创建AppDelegate 类的实例
并作为委托传递给应用程序对象。所以是的,
let appDelegate = UIApplication.shared.delegate as! AppDelegate
是安全的。
但请注意,类名“AppDelegate”并没有什么特别之处,这只是约定。您可以定义应用程序
委托为
@UIApplicationMain
class MyFantasticAppDelegate: UIResponder, UIApplicationDelegate { ... }
在这种情况下当然是
let appDelegate = UIApplication.shared.delegate as! MyFantasticAppDelegate
所以准确的说法是
将UIApplication.shared.delegate 转换为定义为应用程序委托的类的类型不会失败。
按照惯例,该类型是AppDelegate,但不一定是。