0

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

Luda
  • 7,282
  • 12
  • 79
  • 139
  • Have you tried: `myArray[0].property = "new Value"` ? – saurabh Sep 22 '15 at 12:00
  • I just copied your code into a playground and it is working fine. The value is updated and the `secondObject.property` is `"new value"`. – Adam Sep 22 '15 at 12:12
  • 1
    Your code [works in a Playground](https://www.evernote.com/l/AOxKMo-vdbVFkJezcXvFJAoYP4GDWz3I6hs). – Eric Aya Sep 22 '15 at 12:17
  • @sasquatch, I tried it the first thing. But the value was not saved – Luda Sep 22 '15 at 13:30
  • @Adam, I simplified the code t=for the question. I'll update my question with the original code – Luda Sep 22 '15 at 13:31
  • @Eric D., I simplified the code t=for the question. I'll update my question with the original code – Luda Sep 22 '15 at 13:31
  • Can you show the declaration of `myArray`? – saurabh Sep 22 '15 at 13:37
  • I found it!!! The array was singelton property. I was calling MyClass(). myArray, instead of calling MyClass.sharedInstance.myArray – Luda Sep 22 '15 at 20:43

3 Answers3

4

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?

some_id
  • 29,466
  • 62
  • 182
  • 304
  • I found it!!! The array was singelton property. I was calling MyClass(). myArray, instead of calling MyClass.sharedInstance.myArray – Luda Sep 22 '15 at 20:43
0

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.

Community
  • 1
  • 1
Nicholas Allio
  • 717
  • 2
  • 9
  • 28
  • 3
    `object` is not being changed. There is no need to declare it as `var` – saurabh Sep 22 '15 at 11:59
  • I found it!!! The array was singelton property. I was calling MyClass(). myArray, instead of calling MyClass.sharedInstance.myArray – Luda Sep 22 '15 at 20:43
0

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

Luda
  • 7,282
  • 12
  • 79
  • 139