user2434385 user2434385 - 1 year ago 82
Swift Question

Modify Array in swift using if var =

starting swift this past days i'm facing something that looks so simple but this makes me blow my mind.

I have an array myArray which is of type [[String:Any]].

I want simply want to modify an array by adding stuff in it :

if var tempValue = self.myArray[0]["values"] as? [AnyObject] {
// if i print content of self.myArray it is empty
self.matches[0]["values"] = ["hello", "hello2"]
// this lines does work

i do not understand why when i mutate tempValue the referenced array is not mutated ? Is this a new value ?

Thanks for any explanations.

Answer Source

1) [String:Any] is not array, it is Dictionary<String, Any>. I think you mean that myArray have type [[String:Any]]

2) Array and Dictionary types passes by value in swift, not by reference. So tempValue is different instance with same values

You can try this code:

(self.myArray[0]["values"] as? [AnyObject])?.append("hello")
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download