iOS Dev Nugget 181 Swift Selectors


Need to run a code review on your codebase? Hire me

In Objective-C, you can get a selector at compile time with:

SEL selector = @selector(showHelp);

or at runtime:

NSString* str = @"showHelp";
SEL selector = NSSelectorFromString(str);

There's limited type checking.

In Swift, however you have several options. This does minimum checking that there is a method of the same name:

let _ = Selector("showHelp")

This checks if the method is in the current class:

let _ = #selector(showHelp)

This checks if the method is in the specific class/instance:

let _ = #selector(Login.start)
let _ = #selector(Login.sharedInstance.start)

And this makes the compiler check for arguments (and labels):

let _ = #selector(oneArg(_:)) #single arg
let _ = #selector(twoArg(_:two:)) #two arg

Swift has strong type support and it's worthwhile spending some time to learn about it to reduce run-time programming errors.

Your feedback is valuable: Do you want more nuggets like this?   Yes   or   No



Like this and want such iOS dev nuggets to be emailed to you, weekly?

Sign Me Up! or follow @iosdevnuggets on Twitter


View archives of past issues