Search code examples
swiftswift-structspass-by-reference-value

Stopping reference variables changing the value of the original variable


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.


Solution

  • 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.