Pass two arguments to NSTimer in Swift Pass two arguments to NSTimer in Swift swift swift

Pass two arguments to NSTimer in Swift


Make a array with your objects and send it to userInfo. Try this:

func someFunc(){    var arr = ["one", "two"]     var timer: NSTimer = NSTimer.scheduledTimerWithTimeInterval(0.1, target: self, selector: Selector("val:"), userInfo: arr, repeats: true)}func val(timer: NSTimer){    //You'll get an array in timer.userInfo    // arr = timer.userInfo.    // Now you'll get you data in each index of arr}

Hope this helps.. :)


First of all, you've got too many arguments. Secondly, the func receives an NSTimer so you either have to use AnyObject or NSTimer.

So my suggetion would be to use a dictionary or an array and pass that as the userInfo argument like so:

func someFunc(){    var timer: NSTimer = NSTimer.scheduledTimerWithTimeInterval(0.1, target: self, selector: Selector("val:"), userInfo: ["key1" : 1 , "key2" : "aString"], repeats: true)     }func val(val : NSTimer?) {    println("printing \(val?.userInfo)")}


I have modified your code as following.

  1. I have created a NSTimer! variable which will be assigned in someFunc() by method scheduledTimerWithTimeInterval.

  2. then I have set selector as String type (recommended syntax in Swift)

  3. After this I have sent the userInfo which will be retrieved using timer.userInfo in val()

I hope this will help you to solve your problem.

var timer :NSTimer!func someFunc(){       timer = NSTimer.scheduledTimerWithTimeInterval(0.1, target: self, selector: "val", userInfo:"Userinfo", repeats: true)}func val(){       println("printing \(timer?.userInfo) ")}

Note: You can send anything in userInfo. But, off course you have to retrieve the userInfo using timer.userInfo