【问题标题】:Swift dictionary member compile errorSwift字典成员编译错误
【发布时间】:2015-06-01 17:20:10
【问题描述】:

当我将字典设为成员时,分配不会编译:

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 中,我不会收到此错误。

【问题讨论】:

  • 如果你希望你的结构能够修改它的self,你必须这样做:stackoverflow.com/a/30477167/2227743
  • 你是对的。我在“func add”之前添加了“mutating”并修复了它。

标签: swift


【解决方案1】:

您需要像这样从函数声明中添加mutating,因为如果您未在struct 中指定该关键字,则属性是只读的:

mutating func add()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-08-31
    • 2023-03-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多