How to copy a class

Does anyone have advice on how to copy a class? I have been doing some research and understand classes are references types, so when you copy them and make a change to one object property the original class will also change. I had found an article stating that if you change the object during the copy the reference is broken, but I have not been able to make this work. What is the best method for breaking the reference?

Thank you in advance for your help!

Hi @jport1130,
short answer -> Look up the difference between shallow copy and deep copy. What you are looking for is deep copy.

cheers,

To avoid confusion in the future:

‘the class’ = the blueprint

What you want to copy is instances of that class, aka objects.

I found the best way of creating a new object with the same properties as the old object is to design my objects with a settings property which describes the unique features [var customSettings = MyObjectSettings()], as well as an initializer that takes those settings, so [somewhat pseudocode]

let mySettings = MyObjectSettings(property1: “Testing”, property2: 42)

let object1 = MyClass(settings: mySettings)
let object1Copy = MyClass(settings: object1.customSettings)

I found this particularly useful with SpriteKit - SKSpriteNode has lots and lots and lots of properties, and chances are that most of them have default values, so you don’t want to copy (or archive) them - you want to copy/archive only the settings that make your nodes unique.

1 Like

+1 (what he said)

Objects are copied by reference, by default. So preserving the existing properties externally, then creating a new object and using the same properties to initialize it, will give you an object with all of the fields copied.

However, it would be bad design to allow outside code to know or see what those properties are, so some kind of opaque data type is needed to represent them. This is the entire purpose of the Memento design pattern (you know which book to reference for that, right? :wink:)

You don’t really need that if you’re disciplined enough to treat the properties as opaque even when you know they aren’t. For me, I like using JSON as the format of the memento object since it’s very easy to log for debugging purposes, but the conversion to/from JSON could be a performance hit if you’re trying to do this a million times in a tight loop. (Of course, if you’re trying to do it a million times, you should really be asking yourself why you’re not using a struct instead!)

1 Like

This topic was automatically closed after 166 days. New replies are no longer allowed.