0

我做了一些搜索,但仍然无法弄清楚如何解决该错误。基本上我正在从 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:无法分配给“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 文件。

4

1 回答 1

1

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

  1. for你正确编辑的循环中
  2. 因为编译器不知道boo(它只是 an 的一个元素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?!'"
        }
    }
}

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

    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?!'"
        }
    }
于 2016-04-12T13:57:45.663 回答