What does the '@' symbol mean in Swift?

前端 未结 2 1686
醉酒成梦
醉酒成梦 2020-12-09 17:36

I have no experience in objective C, so I\'m having trouble with some of the notation. In my \"AppDelegate.swift\" file, there is a \"@UIMainApplication\" at the top. What d

相关标签:
2条回答
  • 2020-12-09 18:15

    Well, you picked a rather complicated one. The @ merely means that this is an attribute - a special marker or signal to the compiler, as Apple explains here. But @UIApplicationMain is a particularly profound attribute! It substitutes for the entire UIApplicationMain implementation that lies at the heart of a C / Objective-C application, in the main.m file (as I explain here):

    int main(int argc, char *argv[])
    {
        @autoreleasepool {
            return UIApplicationMain(argc, argv, nil,
                                     NSStringFromClass([AppDelegate class]));
        }
    }
    

    That is the main entry point of the app, implementing the entire launch-and-run code that is the running application. You can do something like that in Swift — a main.swift file with the Swift equivalent of that code — but Swift saves you the trouble by letting you designate your app delegate class with the @UIApplicationMain attribute.

    If you start a project as an Objective-C or Objective-C++ project, the template will give you a main file containing the main implementation, so there's no need to do anything special in this regard.

    0 讨论(0)
  • 2020-12-09 18:18

    Keywords starting with an @ are instructions to the compiler – for example, in view controllers you use @IBOutlet to identify variable declarations that relate to connections within the visual interface build (a storyboard or XIB file – the 'IB' prefix stands for 'Interface Builder', which was the old name for the part of Apple's design tools that provided the GUI for visually creating interfaces).

    Put simply, @UIApplicationMain is an indicator for Swift applications that indicates which object is your application's main application delegate file. In Objective-C application templates, you would have a trivial main.m C file which sets the application delegate. With Swift, that trivial implementation becomes a single directive.

    In both cases, the trivial implementation can be replaced with something more complex if need be – but in most apps there is no need for anything else, and indeed if you're only just starting out in Swift, the chances of you needing a non-trivial implementation are most likely to be zero.

    0 讨论(0)
提交回复
热议问题