2015-02-21 6 views
-1

У меня есть функция, которая принимает объект json, содержимое которого может быть любого типа (словаря, массива, строки и т. Д.) И изменяет объект на основе этого типа.swift: изменить словарь на месте

В надуманном примере функции «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) 

ответ

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"]