Understanding Swift 2.2 Selector Syntax - #selector()

前端 未结 4 1659
没有蜡笔的小新
没有蜡笔的小新 2020-12-08 02:13

I am switching over the syntax of my project toward Swift 2.2 (which xCode helps me do automatically); however, I do not understand the new #selector() syntax.<

4条回答
  •  南方客
    南方客 (楼主)
    2020-12-08 03:10

    This is the way Swift method signatures are represented in documentation, and it is now beginning to be used in new language features such as the #selector() syntax to express methods by their argument lists.

    The each colon (:) represents a method parameter. For named parameters, the colon is preceded by the external parameter name; for unnamed parameters, an underscore (_) is used.

    So for example, MyVC.timerCalled(_:)) indicates a method on the MyVC type with one unnamed parameter, which might be declared like this:

    func timerCalled(timer: NSTimer) { ... }
    

    (Note that timer is the internal parameter name, since by default the first parameter of a method is unnamed)

    The type (MyVC in your example) can also be omitted if it is within the same scope of the #selector() declaration.

    A more complex example might look like this:

    let sel = #selector(aMethodWithSeveralParameters(_:secondParam:thirdParam:))
    
    ...
    
    func aMethodWithSeveralParameters(firstParam: Int, secondParam: Int, thirdParam: Int) { ... }
    

提交回复
热议问题