swift: 就地修改字典

swift: modify dictionary in place

我有一个函数接受一个 json 对象,其内容可以是任何类型(字典、数组、字符串等)并根据类型修改对象。

在下面人为设计的示例函数 "foo" 中,我该如何修改字典?我收到编译器错误:

error: '@lvalue $T6' is not identical to '(String, String)'

函数如下

func foo (var item: AnyObject)  {
    // ... other logic that handles item of other types ...    

    // here I know for sure that item is of [String:String] type
    (item as? [String:String])?["name"] = "orange"
    // error: '@lvalue $T6' is not identical to '(String, String)'
}

var fruits = ["name": "apple", "color": "red"]
foo(fruits)

即使您按照 matt 的建议使用 inout 也无法对其进行变异,但您可以克隆 AnyObject 并更改克隆本身并将其克隆回数组 fruits(您还需要包括& 使用inout参数时的前缀:

var fruits:AnyObject = ["name": "apple", "color": "red"]

// var fruits:AnyObject = ["name":2, "color": 3]

func foo (inout fruits: AnyObject)  {
    // ... other logic that handles item of other types ...

    // here I know for sure that item is of [String:Int] type
    if fruits is [String:Int] {
        var copyItem = (fruits as [String:Int])
        copyItem["name"] = 5
        fruits = copyItem as AnyObject
    }
    // here I know for sure that item is of [String:String] type
    if fruits is [String:String] {
        var copyItem = (fruits as [String:String])
        copyItem["name"] = "orange"
        fruits = copyItem as AnyObject
    }
}

foo(&fruits)

fruits  // ["color": "red", "name": "orange"]