我编写了一个堆栈结构,并使其符合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()调用之后它会变成空的。
发布于 2017-06-27 15:09:15
您的for ... in-Loop在堆栈的副本上工作,并且从不更改堆栈本身。如果您自己调用next(),pop()将修改堆栈,如下所示:
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)
}
stack.next()
print(stack.store)输出:
3
2
1
[1, 2]然而,正如@user3581248在评论中指出的那样,使Stack成为类而不是结构(并从其函数中删除mutating )可以为您提供所需的行为。
https://stackoverflow.com/questions/44773810
复制相似问题