In OS Apprentice 3 - MyLocations, p73.
In the NSTimer.scheduledTimerWithTimeInterval() it appears that the “Selector” syntax has changed with Xcode 7.3.
timer = NSTimer.scheduledTimerWithTimeInterval(60, target: self, selector: Selector(“didTimeOut”), userInfo: nil, repeats: false)
…reports the error: "Use #selector instead of explicitly constructing a ‘Selector’
…and want to change it to:
timer = NSTimer.scheduledTimerWithTimeInterval(60, target: self, selector: #selector(CurrentLocationViewController.didTimeOut), userInfo: nil, repeats: false)
First time I’m (we’re) seeing the “#selector”. How would you explain the “#selector” to a 10 year old. Thanks!
didTimeOut is a selector. So is
scheduledTimerWithTimeInterval(_:, target:, selector:, userInfo:, repeats:). It’s the signature of a function.
The problem it solves is this: when you write
Selector("didTimeOut"), “didTimeOut” is a String. The compiler doesn’t test that String to check that it refers to a real function, so if you make a spelling mistake, you don’t find out about it until the program runs.
#selector lets the compiler verify that you’re calling a real function, and that makes your code safer.
Excellent explanation, thanks!
Curious, are there any other “#startswithhash” words that are in swift.
There are a handful. I don’t know them all and I haven’t used them much myself, but generally they’re ‘compiler’ messages in some fashion. A few were introduced with Swift 2.2 - for example, if you write this into a project:
then when it runs it’ll print a message to the console, consisting of the file path of the file in which you wrote the statement, and the number of the line you wrote it on.
Another one is
#available, which you can use to determine things like which operating system your code is being run on, and so only make use of a feature if you know it’s available to that operating system.
Keywords that begin with a number sign (#):
#available, #column, #else #elseif, #endif, #file, #function, #if, #line, and #selector.”
Excerpt From: Apple Inc. “The Swift Programming Language (Swift 2.2).” iBooks. The Swift Programming Language (Swift 5.7) on Apple Books