无法分配给任何对象类型的不可变表达式(cannot assign to immutable expression of type anyobject)

编程入门 行业动态 更新时间:2024-10-25 15:36:24
无法分配给任何对象类型的不可变表达式(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?!' }

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

帮我解决这个问题。

感谢您的时间

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

最满意答案

你的代码中的问题:

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 }

要么

如下所示声明你的arr_contacts2

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

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

更多推荐

本文发布于:2023-07-22 19:30:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1222768.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:表达式   对象   类型   assign   anyobject

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!