我做了一些搜索,但仍然无法弄清楚如何解决错误。 基本上我正在从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的booklist中的isRead。或者甚至更好地更新Book.json文件。
谢谢。
答案 0 :(得分:0)
在您的情况下,您遇到此错误两次:
for
循环中的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?!'"
}
}
}
或者,您为编译器提供有关{/ 1}}
类型的提示boo