skip to Main Content

I am trying to iterate through an array of timers to set each timer equal to nil. I am met with this error:

Cannot assign to value: ‘timer’ is a ‘let’ constant

When I use the following code:

var timers = [Timer?]()

func clearTimers() {
    for timer in timers {
        timer!.invalidate()
        timer = nil
    }
}

2

Answers


  1. Storing an array of optionals doesn’t make much sense, so start by simply declaring your timers array as:

    var timers = [Timer]()
    

    Then you can iterate through the timers to invalidate them and remove all of the references from the array to deallocate them:

    func clearTimers() {
        for timer in timers {
            timer.invalidate()
        }
        timers.removeAll(keepingCapacity:false)
    }
    
    Login or Signup to reply.
  2. The problem is that for timer in timers gives you a new reference — you are not looking at the actual Optional timer in its place in the array. Instead, iterate through the array itself (by way of its indices):

    func clearTimers() {
        for ix in timers.indices {
            timers[ix]?.invalidate()
            timers[ix] = nil
        }
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search