jyet jyet - 3 months ago 7
Swift Question

Why, while loop is running indefinitely here?

I am trying to iterate in reverse order but in the while loop it runs indefinitely and print 4...

func countDown(start: Int) -> AnyIterator<Int> {
var i = start
return AnyIterator {
guard i > 0 else { return nil }
i -= 1
return i
}
}

let i = 5
while let x = countDown(start: i).next() {
print("Element x: \(x)" ) // It iterates indefinitely.
}

Answer

Because the function is being invoked everytime and you're creating a new Iterator everytime.

let  i = 5
let it = countDown(start: i)
while let x = it.next() {
    print("Element x: \(x)" ) // It no longer iterates indefinitely.
}