Alex Ingram
Alex Ingram

Reputation: 434

Swift IF statement to perform action only once

I have an IF statement and I need it to trigger when the score >= 200 but only happen once and not repeatedly.

Here's my code:

if score >= 200 {

        meteRedTimer.invalidate()
        meteBlueTimer = Timer.scheduledTimer(timeInterval: 0.7, target: self, selector: #selector(self.makeBlueMete), userInfo: nil, repeats: true)

    } else {    


    }

However this constantly starts the timer all the time when the score is => 200 and not just one timer which I understand.

If I do score = 200 this would work however there is a chance the score could jump from 190 to 210 for example depending on the game play.

How could I basically stop this IF statement once it has been triggered once?

Upvotes: 0

Views: 822

Answers (3)

vadian
vadian

Reputation: 285092

Declare your timers as optional

var meteBlueTimer : Timer? 
var meteRedTimer : Timer? 

Then check if the timer is not running (nil). Set the invalidated timers to nil.

if score >= 200 && meteBlueTimer == nil {
       meteRedTimer?.invalidate()
       meteRedTimer = nil
       meteBlueTimer = Timer.scheduledTimer(timeInterval: 0.7, target: self, selector: #selector(self.makeBlueMete), userInfo: nil, repeats: true)

} else { ...

Upvotes: 1

rmaddy
rmaddy

Reputation: 318824

Make sure meteBlueTimer is declared as optional.

var meteBlueTimer: Timer?

Then simply check if it is nil or not.

if score >= 200 {
    if meteBlueTimer == nil {
        meteRedTimer.invalidate()
        meteBlueTimer = Timer.scheduledTimer(timeInterval: 0.7, target: self, selector: #selector(self.makeBlueMete), userInfo: nil, repeats: true)
    }
} else {    
}

This way you only create the meteBlueTimer once.

Upvotes: 1

JuicyFruit
JuicyFruit

Reputation: 2668

create var didPermored = false and inside if statement

if score >= 200 && !didPermormed {
    didPermormed = true
    meteRedTimer.invalidate()
    meteBlueTimer = Timer.scheduledTimer(timeInterval: 0.7, target: self, selector: #selector(self.makeBlueMete), userInfo: nil, repeats: true)
} else {    

//do stuff
}

Upvotes: 1

Related Questions