How to copy a struct and modify one of its properties at the same time?

后端 未结 4 867
日久生厌
日久生厌 2021-01-01 17:04

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

4条回答
  •  孤城傲影
    2021-01-01 17:30

    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
    

提交回复
热议问题