Create while loop on timer (swift3)

The code below when compiled is completed instantly. I would like the counter to add 1 every second. So the program should run for 556 seconds. Every second goes by the counter increase by 1.

                   var counter = 0

    while true {

        counter += 1

        print(counter)
        
        if counter == 556 {
            break
        }
    }

Use a Timer. Give it an interval of 1 second, set repeat to true, and give it a function to call every time it fires. The 557th time it fires, you can tell the timer to invalidate and it’ll stop firing.

1 Like