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?
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.
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? )
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!)