1

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

8
  • Have you tried: myArray[0].property = "new Value" ? Commented Sep 22, 2015 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". Commented Sep 22, 2015 at 12:12
  • 1
    Your code works in a Playground. Commented Sep 22, 2015 at 12:17
  • @sasquatch, I tried it the first thing. But the value was not saved Commented Sep 22, 2015 at 13:30
  • @Adam, I simplified the code t=for the question. I'll update my question with the original code Commented Sep 22, 2015 at 13:31

3 Answers 3

5

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?

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

1 Comment

I found it!!! The array was singelton property. I was calling MyClass(). myArray, instead of calling MyClass.sharedInstance.myArray
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.

2 Comments

object is not being changed. There is no need to declare it as var
I found it!!! The array was singelton property. I was calling MyClass(). myArray, instead of calling MyClass.sharedInstance.myArray
0

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

Comments

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.