为什么 mutating function next 在迭代后不会改变结构(符合 Sequence 和 IteratorProtocol)?
Why mutating function next does not change the struct (conforming to Sequence and IteratorProtocol) after the iteration?
我写了一个堆栈结构,并使其符合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()
调用后变空了。
您的 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 成为 class 而不是结构(并从其函数中删除 mutating
)可以为您提供所需的行为。
我写了一个堆栈结构,并使其符合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()
调用后变空了。
您的 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 成为 class 而不是结构(并从其函数中删除 mutating
)可以为您提供所需的行为。