Count down with speed control

I have a number that I would like to visually represent as counting down from x to y on a given event, it is no a timer and so I used the Stride method to achieve this, but it's too quick as I would like to visually convey that information to the user in half/quarter seconds:

    func countDown() {
        
        for i in stride(from: 20, through: 1, by: -1) {
            countLabel.text = String(i)
        }
    }

Is there a method in Swift that allows for more control over the speed of which the counting runs at?

You need to sleep for some period of time within your loop, which is an O/S function. First candidate is the sleep(),nanosleep(),usleep() system calls. sleep() and usleep() are Darwin/Linux, maybe Windows. nanosleep() is on Darwin only, I think. There are other ways of interrupting the thread for a period of time.

First of all, you cannot do this on the main thread, as it will block all other UI updates and cause your app (I'm assuming iOS) to be killed for blocking the main thread. What you are probably looking for is using a timer callback (which I know you said you weren't) or possibly interfacing with CADisplayLink if you need really accurate display.

That said, doing this on a background thread you might be able to accomplish this using what @jonprescott said and wrapping any calls to UI elements in something like this:

...  // within your stride() 
DispatchQueue.main.async {
    countLabel.text = String(i)
}
...

This would not block the main thread and kill your app, but in a broader sense it would be doing unnecessary work if your app isn't even on display.

I see.

I don't know anything about using different threads, so for now I'm going to just change the number and look into it later.

Thanks for the thread, I'll pull it later..

Terms of Service

Privacy Policy

Cookie Policy