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