如何复制结构并同时修改其属性之一? [英] How to copy a struct and modify one of its properties at the same time?
问题描述
如果我想将视图控制器的状态表示为单个结构,然后实施撤消机制,我将如何更改该结构上的一个属性,同时获取前一个状态的副本?
If I want to represent my view controller's state as a single struct and then implement an undo mechanism, how would I change, say, one property on the struct and, at the same time, get a copy of the the previous state?
struct A {
let a: Int
let b: Int
init(a: Int = 2, b: Int = 3) {
self.a = a
self.b = b
}
}
let state = A()
现在我想要一个state
的副本,但b =4.如何在不构造新对象且不必为每个属性指定值的情况下做到这一点?
Now I want a copy of state
but with b = 4. How can I do this without constructing a new object and having to specify a value for every property?
推荐答案
注意,当您为常量 a
和b
使用占位符值时,您将无法构造A
和其他任何值,但此占位符除外.改写初始化器.您也可以编写自定义方法来更改struct中的任何值:
Note, that while you use placeholder values for constants a
and b
you are not able to construct instance of A
with any other values but this placeholders. Write initializer instead. You may write custom method that change any value in struct also:
struct A {
let a: Int
let b: Int
init(a: Int = 2, b: Int = 3) {
self.a = a
self.b = b
}
func changeValues(a: Int? = nil, b: Int? = nil) -> A {
return A(a: a ?? self.a, b: b ?? self.b)
}
}
let state = A()
let state2 = state.changeValues(b: 4)
这篇关于如何复制结构并同时修改其属性之一?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!