Swift 4.1: 字典中的数组未更新

Swift 4.1: array in dictionary not updated

这种奇怪的行为让我很困惑。我打算用一个数组字段创建一个字典。然后在这个数组中,附加了两个额外的子词典。这是代码,

    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。

正如您从调试器输出中看到的那样,var 数组已成功更新(附加了 2 个子词典)。但是 dictionary["array"] 仍然具有 0 值。

看来 (dictionary["array"]) 和 (array) 是两个独立的对象

是的,它们是分开的。元素 dictionary["array"] 是类型 Array<_> 的不可变值,因为它是作为值类型而不是引用类型添加到字典中的。

如果您尝试通过封装字典寻址元素来将 dict1 添加到数组,如下所示:

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

您会看到这样的错误:

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

来自Swift Language docs,重点补充:

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.