试图理解类型属性,例如swift的static和class关键字

时间:2014-12-25 03:13:02

标签: ios iphone swift

我目前正在阅读Swift编程语言,当它到达Type Properties时,它会说“您使用static关键字定义值类型的类型属性,并使用class关键字为类类型键入属性”。 “但静态意味着什么,id是什么?我只是无法得到线索。

1 个答案:

答案 0 :(得分:1)

类型属性是与类型关联的属性,这意味着您不需要类或结构的实际实例来访问它们。 static用于在结构中定义此类属性。例如:

struct Constants {
    static let pi = 3.1416
    static let e = 2.71828
    let phi = 1.618
}

println(Constants.pi)     // prints "3.1416"
println(Constants.e)      // prints "2.71828"
println(Constants.phi)    // Error: 'Constants.Type' does not have a member named 'phi'
println(Constants().phi)  // prints "1.618" when we create an instance