IteratorProtocol
我编写了一个堆栈结构,并使其符合Sequence
协议。next
函数正在变异。所以我想堆栈的迭代会改变结构。
import Foundation
struct Stack<Element> {
var store:[Element] = []
mutating func push(_ element:Element) {
store.append(element)
}
mutating func pop() -> Element? {
return store.popLast()
}
}
extension Stack: Sequence, IteratorProtocol {
mutating func next() -> Element? {
return pop()
}
}
var stack = Stack<Int>()
stack.push(1)
stack.push(2)
stack.push(3)
for s in stack {
print(s)
}
print(stack)
我不明白为什么堆栈没有改变。我想在变异next()
调用之后它会变空。