1

I recently moved from Objective-C to Swift, and I'm having an issue with the following example:

var test: [[String: AnyObject]] = [["value": true]]

var aaa: [String: AnyObject] = test[0]
print(aaa["value"])  // prints Optional(1)
aaa["value"] = false
print(aaa["value"])  // prints Optional(0)

var bbb: [String: AnyObject] = test[0]
print(bbb["value"])  // prints Optional(1) again???

How come the change is not stored in the test array?

Thank you.

1
  • 2
    @Dhivya Both references are not related to the question. Commented Mar 1, 2017 at 11:03

2 Answers 2

4

Swift Dictionary is value type not reference type so you need to set it that dictionary with array after making changes.

var test: [[String: AnyObject]] = [["value": true]]

var aaa: [String: AnyObject] = test[0]
print(aaa["value"])  // prints Optional(1)
aaa["value"] = false
print(aaa["value"])  // prints Optional(0)

//Replace old dictionary with new one
test[0] = aaa    

var bbb: [String: AnyObject] = test[0]
print(bbb["value"])  // prints Optional(0) 

Or You can try simply this way:

test[0]["value"] = false
Sign up to request clarification or add additional context in comments.

4 Comments

But is this only with Dictionary? Should I expect this with Array as well? [[true], [true]] ?
Array of boolean is also value type, so that also not possible, But you can simply set array[0][1] = false No need to first extract value and set it and then replace object in array.
I understand. Thank you so much.
@thedp Welcome mate :)
1

directly change from main array

test[0]["value"] = false

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.