无法分配给任何对象类型的不可变表达式

时间:2016-06-23 05:16:33

标签: ios iphone arrays swift dictionary

var arr_contacts2 = [AnyObject]()

ViewDidLoad(){
for  contacts in info {

            var dict_contact = [String:AnyObject]()

            dict_contact["id"] = contacts.contact_id
            dict_contact["type"] = contacts.type
            dict_contact["value"] = contacts.value

            arr_contacts2.append(dict_contact)
        }
    }


IBAction(){
var dict_contact = arr_contacts2[0]
 dict_contact["value"] = "gg" //Cannot assign to immutable expression of type 'AnyObject?!'
}

为什么我收到此错误? 代码有什么问题?

帮我解决这个问题。

感谢您抽出时间

2 个答案:

答案 0 :(得分:3)

您的代码中的问题:

var dict_contact = arr_contacts2[0] // IT ASSIGNS object of type "AnyObject" to dict_contact
//compiler couldn't possibly know, that dict_contact have a dictionary value

更新您的代码,如下所示

func IBAction(){
    guard let dict_contact = arr_contacts2[0] as? [String:AnyObject]
        else{
            return
        }
    var contactInfo  = dict_contact
    contactInfo["value"] = "gg" //Now it should work
    }

<强> OR

声明您的arr_contacts2如下

var arr_contacts2 = [[String:AnyObject]]()

答案 1 :(得分:1)

arr_contacts2的类型为[AnyObject]

contact的类型为AnyObject

您无法将String分配给contact["value"]

如果您将arr_contacts2更改为[[String: Any]],则应该有效。