0

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!

Mike Simz
  • 3,976
  • 4
  • 26
  • 43
  • 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). – Ben Lu Apr 26 '17 at 21:21
  • Checkout http://stackoverflow.com/questions/27812433/how-do-i-make-a-exact-duplicate-copy-of-an-array for an extension to Array that does deep copies of objects that inherit from Copying protocol. – adamfowlerphoto Apr 26 '17 at 22:35

2 Answers2

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.

Paulw11
  • 108,386
  • 14
  • 159
  • 186
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

Mahmoud Fayez
  • 3,398
  • 2
  • 19
  • 36