Swift字典成员编译错误
当我将字典设为成员时,赋值不会编译:Swift字典成员编译错误,swift,Swift,当我将字典设为成员时,赋值不会编译: struct MyClass { var lists = [String:Int](); init() {} func add() { // this compiles var x = [String:Int](); x["y"] = 3; // this gets the compiler error 'cannot assign to the result of this expression' self.l
struct MyClass {
var lists = [String:Int]();
init() {}
func add() {
// this compiles
var x = [String:Int]();
x["y"] = 3;
// this gets the compiler error 'cannot assign to the result of this expression'
self.lists["y"] = 3;
}
什么是会员资格打破了汇编?如果我将该行放在init()FWIW中,则不会出现此错误。您需要像这样从函数声明中添加
mutating
,因为如果未在结构中指定该关键字,则属性是只读的:
mutating func add()
如果你想让你的结构能够修改它的self
,你必须这样做:你是对的。我在“func add”之前添加了“mutating”,这就解决了它。