I want to execute the following function every 5 seconds. I have seen the other answers to related questions that say to use NSTimer.scheduledTimerWithTimeInterval
but that only works for functions without any arguments.
The function:
func sayHello(name: String) {
println("Hey \(name)!")
}
This is the code I tried:
var timer = NSTimer.scheduledTimerWithTimeInterval(5.0, target: self, selector: Selector("sayHello(\(name))"), userInfo: nil, repeats: true)
But it crashes the app with the error:
Terminating app due to uncaught exception 'NSInvalidArgumentException',
reason: '-[Jake.SwiftApp sayHello(jake)]: unrecognized
selector sent to instance 0x7fcd515640a0'
How do I run the function with the one input parameter?
I believe that you can have your function take the
NSTimer
as an argument, which then allows you to send your data in theuserInfo
like so.I haven't been able to test this so the timer might be malformed, but I think the logic is right.