swift:修改字典到位

时间:2015-02-21 02:05:00

标签: swift mutability

我有一个函数,它接受一个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)

1 个答案:

答案 0 :(得分:0)

即使您使用了暗淡建议的inout,也无法改变它,但您可以克隆AnyObject并更改克隆本身并将其克隆回阵列果实(您还需要包含&使用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"]