user2526811 user2526811 - 5 months ago 82
Swift Question

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

Answer

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]]()
Comments