What is the advantage of updating #selector in Swift 2.3?

I see no problem with the simple method name as a string. I'm just wondering why is this better?

+5
source share
3 answers

This is a huge change. In principle, this closes the largest hole in the tongue.

If you form the Selector as a string literal, and you are not mistaken - it is too simple - or if you correctly formulated it, but this method does not undergo Objective-C, you will encounter a scary message at the runtime Unrecognized selector console message - the most common failure in both Objective-C and Swift. (Do a stack overflow on an "unrecognized selector", you'll see what I mean.)

Now the syntax #selector means that you will form a Selector using a link to a function that the compiler will check at compile time. If you make a mistake, the compiler will stop you. If you do everything right, the compiler will form a Selector for you - right. You do not need to know anything about how to form a Selector string; the compiler does all the work. Thus, your chance to collide in this way is effectively reduced to zero. An โ€œunrecognized selectorโ€ accident is dead as an outsider.

+13
source

Updating #selector allows you to use autocomplete. When using string literals, you can add a typo that would create a runtime error.

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

 #selector(MyController.myMethod) 

It is permissible to remove the class name, which makes it a little cleaner, for example:

 #selector(myMethod) 
+5
source

"Before Swift 2.2, selectors were string literals and error prone, because we, like people, invented and still contributed to typos when we were able to write something without autocompletion."

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

+2
source

Source: https://habr.com/ru/post/1245735/


All Articles