Frederic Frederic - 1 year ago 99
Swift Question

how to add a time function to an variable in swift

I'm trying to figure out how I can write an function that for every 15 seconds adds "1" integer into a variable. So everytime 15 seconds passes: myVar: int += 1

I have tried to setup an timer:

myTimer = NSTimer.scheduledTimerWithTimeInterval(1.0, target: self, selector: #selector(playFunc), userInfo: nil, repeats: true)

Answer Source

Well, just pass 15.0 instead of 1.0 to your timer call like this:

myTimer = NSTimer.scheduledTimerWithTimeInterval(15.0, target: self, selector: #selector(playFunc), userInfo: nil, repeats: true)

Given that you have a variable myVar somewhere in your class

var myVar = 0  // or initialize it to whatever you like

you'll just need to implement playFunc which will be called every 15 seconds by the timer:

func playFunc() {
    self.myVar += 1
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download