旧文:
static在Swift 中表示 “类型范围做用域”,这一律念有两个不一样的关键字,它们分别是
static 和 class 。在非 class 的类型上下文中,咱们统一使用 static 来描述类型做用域,class 关键字 是专门用在 class 类型的上下文中的,能够用来修饰类方法以及类的计算属性。类方法就是静态方法,经过类类型能直接调用。
class 中如今是不能出现类的(静态)存储属性的,咱们若是写相似这样的代码的话:
class MyClass { class var bar: Bar? }
编译时会获得一个错误:ide
这主要是由于在 Objective-C 中就没有类变量这个概念,为了运行时的统一和兼容,暂时不太方便添加这个特性。Apple 表示从此将会考虑在某个升级版本中实装 class 类型的类存储变量,如今的话,咱们只能在 class 中用 class 关键字声明方法和计算属性。
|
“static” methods and properties are now allowed in classes (as an alias for class final). You are now allowed to declare static stored properties in classes, which have global storage and are lazily initialized on first access (like global variables).
|
struct Point {
let x: Double let y: Double // 存储属性 static let zero = Point(x: 0, y: 0) // 计算属性 static var ones: [Point] { return [Point(x: 1, y: 1), Point(x: -1, y: 1), Point(x: 1, y: -1), Point(x: -1, y: -1)] } // 类型方法 static func add(p1: Point, p2: Point) -> Point { return Point(x: p1.x + p2.x, y: p1.y + p2.y) }
}
class SomeClass {
static var storedTypeProperty = "Some value." static var computedTypeProperty: Int { return 27 } class var overrideableComputedTypeProperty: Int { return 107 } static var storedClassProp = "class property not OK"
}
|