0

I have a custom class that I want to copy, but declaring it a Struct is not good for various reasons. My question is, if I make a "copy" in the following way, would I have an entirely new object in which each value (strings, ints, etc) are completely unreferenced to any others? Say:

newObject = Object()
newObject.name = oldObject.name // This is a String
newObject.rank = oldObject.rank // This is an Int
newObject.date = oldObject.date // This is a Date
...

Thanks!

Jacobo Koenig
  • 11,728
  • 9
  • 40
  • 75

1 Answers1

0

String, Date, and Int are all structs, which are copied on assignment. They're stored directly, not indirectly by a reference, so you can never get two Ints to point to the same Int (causing aliasing/state-sharing) because Int isn't indirectly referenced.

I would wrap this up in an initializer or instance method (.deepCopy(), perhaps?)

What you have to look out for is accidental aliasing of objects (instances of classes), which are held be references (the references are copied, not the objects they point to). In that case, you would have to recursively call deepCopy on all transitively references objects.

Alexander
  • 59,041
  • 12
  • 98
  • 151
  • An additional information can be found in this post about good practices for objects coping https://stackoverflow.com/questions/24242629/implementing-copy-in-swift – dede.exe Feb 23 '18 at 02:01