1

I have a method that does the following:

let object = sportsArray[0]
let newObject = object
newObject.items?.removeAll()

When I do this the 'newObject' 'items' array is now empty which is what I want, but it also is emptying the 'items' array in 'object'..what am I doing wrong here? How do I prevent this from happening. I want to make changes to newObject without those changes affecting the original object. Any help would be greatly appreciated on this. Thanks in advance!

2
  • What's the type of object? Is it a class or a struct? Struct can be implicitly copied while class needs .copy() to be explicitly copied (if it conforms to NSCopying ofc). Commented Apr 26, 2017 at 21:21
  • Checkout stackoverflow.com/questions/27812433/… for an extension to Array that does deep copies of objects that inherit from Copying protocol. Commented Apr 26, 2017 at 22:35

2 Answers 2

2

sportsArray[0], object and newObject are all references to the same class instance. When you change that instance using any of the references, the other references will reflect that change since they refer to the same thing.

You need to explicitly create a new instance of your object using an initialiser or .copy.

Sign up to request clarification or add additional context in comments.

Comments

1

You can try this, obviously you need to replace ClassName with the real class name

let newObject = ClassName(object)

If your class implements NSCopy you can use object.copy() too.

Take a look on how to define new initialize that takes one argument here: https://developer.apple.com/library/content/documentation/Swift/Conceptual/Swift_Programming_Language/Initialization.html

2 Comments

This one doesn't seem to work. "Argument passed to call that takes no argument"
You have to create a new intializer function that takes same argument to resolve the compile error or implement NSCopy

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.