Luda
Luda

Reputation: 7068

Swift updating property of an object in Array, doesn't work

I trying to update property of an object in an array and it doesn't work. I tried replacing the whole object in the array, but it didn't help

let object = myArray[0]
object.property = "new value"
myArray[0] = object
print(object.property) //"new value"

let sameObject = myArray[0]
print(sameObject.property) //"old value"

EDIT: I found it!!! The array was singelton property. I was calling MyClass().myArray, instead of calling MyClass.sharedInstance.myArray

Upvotes: 1

Views: 1587

Answers (3)

Luda
Luda

Reputation: 7068

I found it!!! The array was singelton property. I was calling MyClass(). myArray, instead of calling MyClass.sharedInstance.myArray

Upvotes: 0

Nicholas Allio
Nicholas Allio

Reputation: 769

I think is because you are declaring the array let: it means that it will remain unchanged. Try to declare it as var and then it should work.

EDIT You are right, I think I misunderstood your question then; but i found this answer that can be useful; at the end you should declare it var.

Upvotes: 0

some_id
some_id

Reputation: 29896

This depends on what it is in the array. If its a class it will be a reference to the instance. If it is a struct, you will get a copy of it when you assign, leading to the changes you made to the copy not being applied to the object.

What is in the array?

Upvotes: 5

Related Questions