简体   繁体   中英

cannot assign to immutable expression of type anyobject

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?!'
}

Why I am getting this error? What is the wrong with the code?

Help me to solve this.

Thank you for your time

ISSUE IN YOUR CODE:

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

UPDATE YOUR CODE as below

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

Declare your arr_contacts2 as below

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

arr_contacts2 is of type [AnyObject] .

contact is of type AnyObject .

You cannot assign a String to contact["value"] .

It should work if you change arr_contacts2 to [[String: Any]] .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM