如何在 Swift 中使可变性敏感 Class?

How to make mutability sensitive Class in Swift?

我有自定义数组-class,例如:

public typealias JsonValue = AnyHashable;

public class Json {
    public private(set) var raw: NSMutableDictionary

// ...

    public subscript(key: String) -> JsonValue? {
        get {
            return self.raw[key];
        }
        set(value) {
            raw[key] = value;
        }
    }
}

以后像这样使用它:

var myVariable = Json();
myVariable["key"] = "value";

但是 Swift 警告如下:

Variable 'myVariable' was never mutated; consider changing to 'let' constant

如何告诉 Swift 我正在变异 myVariable

I already tried mutating keyword, but that resulted in error (telling not allowed on setter).

I am using Swift 5 on Xcode 12.

您的变量具有引用 (class) 类型,因此该变量仅包含对 class 实例的 引用,并且未发生变化.

struct(值类型)和class(引用类型)有很大区别。在这种情况下,您应该将声明更改为:

let myVariable = Json()

要用引用类型改变变量,您必须分配一个新实例,例如

myVariable = Json()

You seem to want value semantics for your Json type. If so, just make it a struct. For more info, see the Swift Guide