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

后端 未结 4 866
日久生厌
日久生厌 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:15

    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"}
    

提交回复
热议问题