Ryan Tobin
Ryan Tobin

Reputation: 224

Iterate For Loop Overtime in Swift

How can I iterate a for loop overtime in swift? A typical loop will execute immediately as fast as possible. However, I would like to expand the time in which the loop occurs. Say I have the following loop:

for var i = 0; i < 4; i+=1{
        print(i)
}

And I wanted this loop to occur over a span of 1 second, each iteration taking 0.25 seconds. How could I do this? Thanks for any help

Upvotes: 0

Views: 113

Answers (1)

Luinily
Luinily

Reputation: 66

You might want to create a Timer like this:

timer = NSTimer.scheduledTimerWithTimeInterval(0.25, target: self,   selector: #selector(MyClass.tic), userInfo: nil, repeats: true)
time.fire() //first time

this timer will call the function selected with #selector when it fires, and will fire every 0.25 secondes (first parameter) until you invalidate it. So when you have ended your loops you can call timer.invalidate()

tic() is a function you can define, and can have any name you want:

func tic() {
    numberOfTimeFired = numberOfTimeFired + 1
    print(numberOfTimeFired)
}

In Swift 3 the timer declaration would be:

timer = Timer.scheduledTimer(timeInterval: 0.25, target: self, selector: #selector(MyClass.tic), userInfo: nil, repeats: true)

Upvotes: 1

Related Questions