2

I am assigning the value of a custom class to another variable. Updating the value of the new variable is affecting the value of the original variable. However, I need to stop the reference variable from updating the original variable.

Here's a basic representation of what's happening:

var originalVariable = CustomClass()

originalVariable.myProperty = originalValue

var referenceVariable = originalVariable 

referenceVariable.myProperty = updatedValue

print("\(originalVariable.myProperty)") //this prints the ->updatedValue<- and not the ->originalValue<-

I've tried wrapping the referenceVariable in a struct to make it a value type but it hasn't solved the problem.

I've found information regarding value and reference types but I haven't been able to find a solution.

My question in a nutshell: How do I stop an update to a reference variable from updating the original variable that it got its value assigned from?

Thanks in advance.

Hamish
  • 78,605
  • 19
  • 187
  • 280
Micah Simmons
  • 2,078
  • 2
  • 20
  • 38
  • Instead of using a class for CustomClass, can you make this a struct instead? The issue is that a class is a reference and when you do var reference = originalVariable you are just creating a reference to originalVariable and not a copy. – totiDev Jun 08 '17 at 08:52
  • 1
    This is what make class a class, if you do not wish for this pointer feature, use Struct instead – Tj3n Jun 08 '17 at 08:59
  • Thanks for your responses. I tried changing CustomClass to a struct and that has solved the issue. I had tried putting the reference variable in a struct, but, that didn't work though. I tried using the NSObject approach but the copy method doesn't seem to be available to be called on an array of CustomClasses so it won't work for the project that I'm working on. But, I think that there are other ways to copy arrays. Cheers. – Micah Simmons Jun 08 '17 at 09:18

1 Answers1

2

The whole point of reference semantics (as used by classes) is that all variables point to the same (i.e., they reference the same) object in memory. If you don't want that behaviour, you should use value types (Struct, Enum, Array...) or create copies of your object.

If CustomClass implements the NSCopying protocol you can do:

var referenceVariable = originalVariable.copy()

If it doesn't, you'll have to find some other way to copy it or implement the protocol yourself.

Wrapping the class in a struct will just make two different structs each containing a different reference to the same object.

Matusalem Marques
  • 2,399
  • 2
  • 18
  • 28