I have a function that takes a json object whose contents can be of any type (dictionary, array, string, etc) and modifies the object based on the type.
In the contrived example function "foo" below, how can I modify the dictionary in place? I get the compiler error:
error: '@lvalue $T6' is not identical to '(String, String)'
Here's the function
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)
You won't be able to mutate it even if you use the inout as suggested by matt but you can clone your AnyObject and change the clone itself and clone it back to the array fruits (you also need to include the & prefix when using inout parameter:
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"]