Search code examples
arraysswifttimercountdowntimer

With an array of int values, how to create a timer that counts down from each int value in the array? (Swift)


The values in the array are placed by the user, so there could be any number of values in the array. If the first value in the array is 5, then the timer on the screen counts from 5 seconds to 0 seconds, then if the second value is 10, then the timer automatically starts counting down from 10 to 0 and stops if that is the last value in the array or continues if there are more.


Solution

  • When solving this question, you need to identify the problem which is how do you change which index should the timer take its timing from.

    import Foundation
    
    var times = [10,20]
    
    var index = 0
    
    var time = times[index]
    
    let timer = Timer.scheduledTimer(withTimeInterval: -1, repeats: true, block: { timer in
        
        print(time)
        
        time -= 1
        
        //reset only when it becomes -1 so you can see 0
        if time == -1 {
            
            if index < times.count - 1{
                //increase the index by 1; which is the next timing set
                
                index += 1
                
                time = times[index]
            } else {
                //invalidate if the index matches the number of count
                timer.invalidate()
            }
        }
    })
    
    timer.fire()
    

    This listing shows how this problem is solved by increasing the index by 1 every time it reaches -1 (so that it can show 0) and setting the time to whatever the time is in that index.

    Once the index is equals to the (times.count - 1), the timer is invalidated because if it is equals to that then it will fall out of range.