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
If you can live with the properties being mutable, this is an alternative approach. Advantage is that it works for every struct and there's no need to change the function upon adding a property:
struct A {
var a: Int
var b: Int
func changing(change: (inout A) -> Void) -> A {
var a = self
change(&a)
return a
}
}
let state = A(a: 2, b: 3)
let nextState = state.changing{ $0.b = 4 }
You could also have an extension for this:
protocol Changeable {}
extension Changeable {
func changing(change: (inout Self) -> Void) -> Self {
var a = self
change(&a)
return a
}
}
extension A : Changeable {}
Also you can use this to do it without any additional code:
let nextState = {
var a = state
a.b = 4
return a
}()
And if you don't mind the new struct being mutable, it's just
var nextState = state
nextState.b = 4