jgtww
jgtww

Reputation: 33

Swift 4.1: array in dictionary not updated

This strange behavior baffles me. I intend to create a dictionary with a single array field. Then within this array, two extra sub dictionaries are appended. Here is code,

    var dictionary = [String: Any]()
    var array = [[String: Any]]()
    dictionary["array"] = array

    var dict1:[String:Any] = ["abc": 123, "def": true]
    var dict2:[String:Any] = ["111": 1.2345, "222": "hello"]
    array.append(dict1)
    array.append(dict2)

Debugger output.

enter image description here

As you can see from the debugger output, the var array is updated successfully (with 2 sub dictionaries appended). But the dictionary["array"] still has 0 value.

It appears the (dictionary["array"]) and (array) are two separate objects

Upvotes: 0

Views: 354

Answers (1)

Craig
Craig

Reputation: 9330

Yes, they are separate. The element dictionary["array"] is an immutable value of type Array<_> because it's added as a value type to the dictionary not a reference type.

If you tried to add dict1 to the array by addressing the element via it's encapsulating dictionary like this:

(dictionary["array"] as! Array).append(dict1)

You would see an error like this:

error: cannot use mutating member on immutable value of type 'Array<_>'

From the Swift Language docs, emphasis added:

A value type is a type whose value is copied when it is assigned to a variable or constant, or when it is passed to a function.

You’ve actually been using value types extensively throughout the previous chapters. In fact, all of the basic types in Swift—integers, floating-point numbers, Booleans, strings, arrays and dictionaries—are value types, and are implemented as structures behind the scenes.

Upvotes: 1

Related Questions