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 s
The best way I have found is to write an initializer method that takes an object of the same type to "copy", and then has optional parameters to set each individual property that you want to change.
The optional init parameters allow you to skip any property that you want to remain unchanged from the original struct.
struct Model {
let a: String
let b: String
init(a: String, b: String) {
self.a = a
self.b = b
}
init(model: Model, a: String? = nil, b: String? = nil) {
self.a = a ?? model.a
self.b = b ?? model.b
}
}
let model1 = Model(a: "foo", b: "bar")
let model2 = Model(model: model1, b: "baz")
// Output:
// model1: {a:"foo", b:"bar"}
// model2: {a:"foo", b:"baz"}