thedp
thedp

Reputation: 8516

Can't update a value in a Dictionary inside an Array?

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.

Upvotes: 1

Views: 670

Answers (2)

anshul king
anshul king

Reputation: 568

directly change from main array

test[0]["value"] = false

Upvotes: 1

Nirav D
Nirav D

Reputation: 72450

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

Upvotes: 4

Related Questions