Difference between Structure vs class in swift

person shubham sharmafolder_openiOS, Swiftlocal_offer, access_time March 26, 2019

Here’s an example with a class. Note how when the name is changed, the instance referenced by both variables is updated. Bob is now Sue, everywhere that Bob was ever referenced.

 

And now with a struct we see that the values are copied and each variable keeps it’s own set of values. When we set the name to Sue, the Bob struct in aStruct does not get changed.

 

So for representing a stateful complex entity, a class is awesome. But for values that are simply a measurement or bits of related data, a struct makes more sense so that you can easily copy them around and calculate with them or modify the values without fear of side effects.

warningComments are closed.