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
I really like @Shadow answer, but I had a hard time adapting it to a scenario were the fields of the struct could be nullable, so I decided to use the builder pattern instead. My code looks something like this:
struct A {
let a: Int?
let b: Int?
class Builder {
private var a: Int?
private var b: Int?
init(struct: A) {
self.a = struct.a
self.b = struct.b
}
func build() -> A {
return A(a: self.a, b: self.b)
}
func withA(_ a: Int?) -> Builder {
self.a = a
return self
}
func withB(_ b: Int?) -> Builder {
self.b = b
return self
}
}
}
And then you can use it like:
A.Builder(struct: myA).withA(a).withB(nil).build()
With this my structs are really immutable, and I can quickly create a copy and change one or many of its field to be either nil
or another Int