In the following code, c is a constant sequence (an instance of Countdown), it can iterate through its elements and break when the condition is met, and it can iterate from the start again.
But when I call c.next() directly, I get a compiler error: cannot use mutating member on immutable value.
So, I have two questions:
- If I cannot call
c.next(), why can it iterate through all the elements in the first place? Isn't it using thenext()method internally to iterate through them? - In the second
for-inloop in the following code, why is it not counting from1where the first iteration left off, instead it counts from the start, which is3?
struct Countdown: Sequence, IteratorProtocol {
// internal state
var count: Int
// IteratorProtocol requirement
mutating func next() -> Int? {
if count == 0 { return nil } else {
defer { count -= 1 }
return count
}
}
}
// a constant sequence
let c = Countdown(count: 3)
// can iterate and break
for i in c {
print(i) // 3, 2
if i == 2 { break }
}
// iterate again from start (not from 1, why?)
for i in c { print(i) } // 3, 2, 1
// ⛔️ Error: cannot use mutating member on immutable value.
// `c` is a `let` constant.
c.next()