I was trying out the use of Sequence and IteratorProtocol. But something here surprised me. There is no error on the for statement but the while statement has the error "Cannot use mutating member on immutable value: 'threeToGo' is a 'let' constant".
This looks like an inconsistency in Swift. They are both mutating the threeToGo variable. Can anyone give an explanation?
func even(_ i: Int) -> Bool { i % 2 == 0 }
struct Countdown: Sequence, IteratorProtocol {
var count: Int
mutating func next() -> Int? {
if count == 0 {
return nil
} else {
defer { count -= 1 }
return count
}
}
}
let threeToGo = Countdown(count: 3)
while let i = threeToGo.next() {
print(i)
if even(i) { break }
}
print("We broke out")
for i in threeToGo {
print(i)
}