What's the advantage of #selector update in Swift 2.3?

后端 未结 3 1440
孤城傲影
孤城傲影 2021-01-19 00:53

I can\'t see a problem with just writing the method name as a string. Im just curious as to why this is better?

相关标签:
3条回答
  • 2021-01-19 01:24

    “Before Swift 2.2, selectors were string literals and prone to error because we, as humans invented, and still contribute to typos whenever given the chance to write something without autocomplete.”

    https://medium.com/swift-programming/swift-selector-syntax-sugar-81c8a8b10df3#.8ki9dd38j

    0 讨论(0)
  • 2021-01-19 01:32

    This is a huge change. Basically, this closes the biggest crash-hole in the language.

    If you form a Selector as a string literal, and you form it wrong — which is all too easy — or if you form it right but the method in question is not exposed to Objective-C, you will crash at runtime with the dreaded Unrecognized selector console message — the most common crash in both Objective-C and Swift. (Do a Stack Overflow on "unrecognized selector"; you will see what I mean.)

    Now, the #selector syntax means that you will form the Selector using a function reference, which the compiler will check at compile time. If you make a mistake, the compiler stops you dead. If you do it right, the compiler forms the Selector for you — correctly. You don't need to know anything about how to form the Selector string; the compiler does all the work. Thus, your chance of crashing in this way is effectively reduced to zero. The "unrecognized selector" crash is dead as a doornail.

    0 讨论(0)
  • 2021-01-19 01:34

    The #selector update lets you use autocomplete. When using string literals, you could add a typo which would create a run-time error.

    Just to add, when using the migration tool in Xcode, Xcode will change your selector to something like:

    #selector(MyController.myMethod)
    

    It's acceptable to remove the class' name which makes it a little cleaner, like so:

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