Swift: 为什么非静态方法不能调用没有dynamicType 的静态变量和常量(static let)?

Swift: Why the non-static methods can't call static variables and constant (static let) without dynamicType?

使用swift后,它破坏了我对静态变量和常量的看法。

为什么swift不允许我们在其他方法中调用静态变量和常量?

例如:

class Aa {
    static let name = "Aario"
    func echo() {
        print(name)      // Error!
    } 
}

先生食人魔告诉我使用 dynamicType .

class Aa {
    static var name = "Aario"
    func echo() {
        print(self.dynamicType.name)
    }
}

let a = Aa()
a.dynamicType.name = "Aario Ai"   
a.echo()                         // it works!!!

有效!那为什么要用dynamicType来调用静态变量呢?

最后的答案是:

class Aa {
    static var name = "Static Variable"
    var name = "Member Variable"
    func echo() {
        print(self.dynamicType.name)    // Static Variable
        print(Aa.name)                  // Static Variable
        print(name)                     // Member Variable
    }
}

let a = Aa()
a.dynamicType.name = "Aario Ai"   
Aa.name = "Static: Aario"
a.name = "Member: Aario"
a.echo()                         // it works!!!

和其他语言真的不一样。

静态变量必须用它们的类型来寻址,即使您在这种类型中编写代码也是如此。参见 The Swift Programming Language (Swift 2.2) - Properties(在 "Querying and Setting Type Properties" 中):

Type properties are queried and set with dot syntax, just like instance properties. However, type properties are queried and set on the type, not on an instance of that type.

在您的代码中,只需写 Aa.name 而不是 name 就可以了。