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
Storing an array of optionals doesn’t make much sense, so start by simply declaring your
timers
array as:Then you can iterate through the timers to invalidate them and remove all of the references from the array to deallocate them:
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 itsindices
):