人们如何处理迭代Swift结构的value-type属性? [英] how do people deal with iterating a Swift struct value-type property?
问题描述
在这里,人们必须时时刻刻出现这种明显的情况:
Here's an obvious situation that must arise all the time for people:
struct Foundation {
var columns : [Column] = [Column(), Column()]
}
struct Column : CustomStringConvertible {
var cards = [Card]()
var description : String {
return String(describing:self.cards)
}
}
struct Card {}
var f = Foundation()
for var c in f.columns {
c.cards.append(Card())
}
该代码是合法的,但对f
毫无影响,因为var c
仍是副本,而f
的实际columns
不受影响.
That code is legal but of course it has no effect on f
, because var c
is still a copy — the actual columns
of f
are unaffected.
我理解为什么会发生为什么没有任何困难.我的问题是人们对此通常做.
I am not having any difficulties understanding why that happens. My question is what people generally do about it.
很显然,我可以通过将Column声明为 class 而不是 struct 来解决整个问题,但这是人们通常会做的事情吗? (我试图遵循一种精神上的严格要求,即在不需要动态调度/多态性/子类化时应该避免使用类;也许我对此进行了过多讨论,或者人们通常会做其他事情,例如使用inout
不知何故.)
Clearly I can just make the whole matter go away by declaring Column a class instead of a struct, but is that what people usually do? (I'm trying to follow a mental stricture that one should avoid classes when there's no need for dynamic dispatch / polymorphism / subclassing; maybe I'm carrying that too far, or maybe there's something else people usually do, like using inout
somehow.)
推荐答案
从Swift 4开始,一种折衷方法是迭代可变集合的索引,而不是元素本身,以便
As of Swift 4, a compromise is to iterate over the indices of a mutable collection instead of the elements themselves, so that
for elem in mutableCollection {
// `elem` is immutable ...
}
或
for var elem in mutableCollection {
// `elem` is mutable, but a _copy_ of the collection element ...
}
成为
for idx in mutableCollection.indices {
// mutate `mutableCollection[idx]` ...
}
在您的示例中:
for idx in f.columns.indices {
f.columns[idx].cards.append(Card())
}
正如@Hamish在评论中指出的那样,Swift的未来版本可能会实现
As @Hamish pointed out in the comments, a future version of Swift may implement a mutating iteration, making
for inout elem in mutableCollection {
// mutate `elem` ...
}
可能.
这篇关于人们如何处理迭代Swift结构的value-type属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!