【问题标题】:cannot assign to immutable expression of type anyobject不能分配给 anyobject 类型的不可变表达式
【发布时间】:2016-06-23 05:16:33
【问题描述】:
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?!'
}

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

帮我解决这个问题。

感谢您的宝贵时间

【问题讨论】:

  • 试试这样if let dict_contact = arr_contacts2[0] as? [String:AnyObject] { dict_contact["value"] = "gg" }
  • @EICaptainv2.0,感谢您的回答。我不能直接改成arr_contacts2[0]["value"] = "gg"这样的数组吗?
  • @EICaptainv2.0,如何直接更改数组中字典的值?

标签: ios iphone arrays swift dictionary


【解决方案1】:

代码中的问题:

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

【讨论】:

  • 感谢您的回答。我不能直接变成像 arr_contacts2[0]["value"] = "gg" 这样的数组吗?
  • var dict_contact = arr_contacts2[0] // IT 将“AnyObject”类型的对象分配给 dict_contact //编译器不可能知道,dict_contact 有一个字典值,所以你可以直接操作它,首先你需要施放它!!
  • 好的,如何直接更改数组中字典的值?
  • 将 arr_contacts2 声明为 => var arr_contacts2 = [[String:AnyObject]]()
【解决方案2】:

arr_contacts2 的类型为 [AnyObject]

contact 的类型为 AnyObject

您不能将String 分配给contact["value"]

如果您将arr_contacts2 更改为[[String: Any]],它应该可以工作。

【讨论】:

    猜你喜欢
    • 2016-08-02
    • 2015-11-12
    • 2017-05-16
    • 1970-01-01
    • 2019-10-30
    • 2017-04-14
    • 2023-01-18
    • 2019-04-06
    • 1970-01-01
    相关资源
    最近更新 更多