【问题标题】:Cannot assign to immutable expression of type ' AnyObject?!'无法分配给“AnyObject?!”类型的不可变表达式
【发布时间】:2016-08-02 19:23:48
【问题描述】:

我进行了一些搜索,但仍然无法弄清楚如何解决该错误。 基本上我正在从 Json 文件中读取书单,然后对其进行更新。读取部分没问题,但尝试更新时发生错误(“无法分配给类型为‘AnyObject?!’的不可变表达式”)。

var url = NSBundle.mainBundle().URLForResource("Book", withExtension: "json")

var data = NSData(contentsOfURL: url!)

var booklist = try! NSJSONSerialization.JSONObjectWithData(data!, options: []) as! NSMutableArray


for boo in booklist {
            if (boo["name"]  as! String) == "BookB" {
                print (boo["isRead"]) //see Console Output
                boo["isRead"] = "true"  //this gets error "Cannot assign to immutable expression of type ' AnyObject?!'"
            }

Json 文件 Book.json 如下:

[
{"name":"BookA","auth":"AAA","isRead":"false",},
{"name":"BookB","auth":"BBB","isRead":"false",},
{"name":"BookC","auth":"CCC","isRead":"false",},
]

书单有预期值,见控制台输出:

(
        {
        name = BookA;
        auth = AAA;
        isRead = false;
    },
        {
        name = BookB;
        auth = BBB;
        isRead = false; 
    },
       {
        name = BookC;
        auth = CCC;
        isRead = false;
    }
)

对于print (boo["isRead"]),控制台结果为Optional(false),这是正确的。

Booklist已经是NSMutableArray了,我也试过改成

var booklist = try! NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.MutableContainers) as! NSMutableArray

但它没有帮助。

也指Swift: Cannot assign to immutable expression of type 'AnyObject?!',改成下面也报同样的错误:

var mutableObjects = booklist
for var boo in mutableObjects {
            if (boo["name"]  as! String) == "BookB" {
                print (boo["isRead"]) //see Console Output
                boo["isRead"] = "true"  //this gets error "Cannot assign to immutable expression of type ' AnyObject?!'"
            }

在这种情况下,任何人都可以建议如何更新 BookB 的书单中的 isRead。或者更好的方法是更新 Book.json 文件。

【问题讨论】:

标签: json swift nsmutablearray immutablearray


【解决方案1】:

在您的情况下,您两次遇到此错误:

  1. 在您正确编辑的for 循环中
  2. 因为编译器不知道boo 的类型(它只是NSMutableArray 的一个元素)

要解决这个问题,你可以这样写:

for var boo in mutableObjects {
    if var theBoo = boo as? NSMutableDictionary {
        if (theBoo["name"]  as! String) == "BookB" {
            print (theBoo["isRead"]) //see Console Output
            theBoo["isRead"] = "true"  //this gets error "Cannot assign to immutable expression of type ' AnyObject?!'"
        }
    }
}

或者,你给编译器一个关于boo类型的提示:

    guard let theBoos = mutableObjects as? [Dictionary<String, AnyObject>] else {
        return
    }

    for var theBoo in theBoos {
        if (theBoo["name"]  as! String) == "BookB" {
            print (theBoo["isRead"]) //see Console Output
            theBoo["isRead"] = "true"  //this gets error "Cannot assign to immutable expression of type ' AnyObject?!'"
        }
    }

【讨论】:

    猜你喜欢
    • 2015-11-12
    • 2017-05-16
    • 1970-01-01
    • 1970-01-01
    • 2017-04-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-01-18
    相关资源
    最近更新 更多