Frederic
Frederic

Reputation: 497

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)

Upvotes: 0

Views: 52

Answers (2)

RyanM
RyanM

Reputation: 761

You could simply change this:

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

to this: (Changing 1.0 to 15.0)

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

Or you could do this:

var timesPlayed = 0

func playFunc() {
    timesPlayed += 1

    if timesPlayed % 15 == 0 {
        myVar += 1
    }
}

What this does is every time the function is run it will try see if it is dividable by 15 and if so then it means the function has run 15 times which will then add 1 to your variable.

Upvotes: 0

Keiwan
Keiwan

Reputation: 8251

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
}

Upvotes: 1

Related Questions