我试图以相反的顺序迭代但是在while循环中它无限期地运行并打印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.
}
答案 0 :(得分:1)
因为每次都会调用该函数,并且每次都在创建一个新的迭代器。
let i = 5
let it = countDown(start: i)
while let x = it.next() {
print("Element x: \(x)" ) // It no longer iterates indefinitely.
}