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

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

    Note, that while you use placeholder values for constants a and b you are not able to construct instance of A with any other values but this placeholders. Write initializer instead. You may write custom method that change any value in struct also:

    struct A {
        let a: Int
        let b: Int
    
        init(a: Int = 2, b: Int = 3) {
            self.a = a
            self.b = b
        }
    
        func changeValues(a: Int? = nil, b: Int? = nil) -> A {
            return A(a: a ?? self.a, b: b ?? self.b)
        }
    }
    
    let state = A()
    let state2 = state.changeValues(b: 4)
    

提交回复
热议问题