swag swag - 5 months ago 19
Swift Question

How to make time delay repeat infinitely in swift

I have this code and it calls a function called tapped coin but I need this delay function to continue to repeat indefinitely so the user can simulate this automatic tap.

delay(1){
for i in 0...5{
print(i)
self.tappedCoin()
}
}


The delay function looks like this

func delay(delay:Double, closure:()->()) {
dispatch_after(
dispatch_time(
DISPATCH_TIME_NOW,
Int64(delay * Double(NSEC_PER_SEC))
),
}


How can I get this to continue repeating every second without affecting anything else in the code?

Answer

Something like this? You can stop this loop by assigning coinsEnabled = false

var coinsEnabled = true
var counter = 0

func infiniteLoop() {
    print(counter)
    tappedCoin()
    delay(1) {
        if self.coinsEnabled {
            self.counter += 1
            self.infiniteLoop()
        }
    }
}