Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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 same time, get a copy of the the previous state?

struct A {    let a: Int    let b: Int     init(a: Int = 2, b: Int = 3) {       self.a = a       self.b = b    } }  let state = A() 

Now I want a copy of state but with b = 4. How can I do this without constructing a new object and having to specify a value for every property?

like image 785
Ian Warburton Avatar asked Jul 12 '16 14:07

Ian Warburton


People also ask

Can struct be copied?

In C/C++, we can assign a struct (or class in C++ only) variable to another variable of same type. When we assign a struct variable to another, all members of the variable are copied to the other struct variable.

How do you copy a struct in Swift?

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.

How do you copy a structure in Golang?

A struct variable in Golang can be copied to another variable easily using the assignment statement(=).


1 Answers

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) 
like image 156
Shadow Of Avatar answered Sep 19 '22 13:09

Shadow Of