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

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

    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

提交回复
热议问题