Swift 中表示“类型范围作用域”这一概念有两个不同的关键字,它们分别是 static 和 class。
在非 class 的类型上下文中,我们统一使用 static 来描述类型作用域。这包括在 enum 和 struct 中表述类型方法和类型属性时。在这两个值类型中,我们可以在类型范围内 声明并使用存储属性,计算属性和方法。static 适用的场景有这些:
struct PointAB {
let x : Double
let y : Double
// 存储属性
static let zero = PointAB(x: 0, y: 0)
// 计算属性
static var ones: [PointAB] {
return [PointAB(x: 1, y: 1),
PointAB(x: -1, y: 1),
PointAB(x: 1, y: -1),
PointAB(x: -1, y: -1)]
}
// 类型方法
static func add(p1: PointAB, p2: PointAB) -> PointAB {
return PointAB(x: p1.x + p2.x, y: p1.y + p2.y)
}
}
protocol MyProtocol {
static func foo() -> String
}
struct MyStruct:MyProtocol {
static func foo() -> String {
return "MyStruct"
}
}
enum MyEnum:MyProtocol {
static func foo() -> String {
return "MyEnum"
}
}
class MyClass: MyProtocol {
static func foo() -> String {
return "MyClass"
}
}
来自:swift-喵神