Swift 3 协议中的静态关键字
Static keyword in Swift 3 protocol
我注意到 Swift
protocols
中的某些函数具有 static
关键字。但是,当您实现该功能时,您必须删除 static
关键字以使编译器满意。
public static func <(lhs: Self, rhs: Self) -> Bool
static
在上下文中是什么意思,它的目的是什么?
来自 Xcode 8 beta 4 发行说明:
Operators can be defined within types or extensions thereof. For
example:
struct Foo: Equatable {
let value: Int
static func ==(lhs: Foo, rhs: Foo) -> Bool {
return lhs.value == rhs.value
}
}
Such operators must be declared as static
(or, within a class,
class final
), and have the same signature as their global
counterparts. As part of this change, operator requirements declared
in protocols must also be explicitly declared static
:
protocol Equatable {
static func ==(lhs: Self, rhs: Self) -> Bool
}
静态属性和方法
Swift 允许您创建属于某个类型的属性和方法,而不是属于某个类型的实例。这有助于通过存储共享数据来有意义地组织数据。
Swift 调用这些共享属性 "static properties",您只需使用 static 关键字即可创建一个。完成后,您可以使用类型的全名访问 属性。这是一个简单的例子:
struct TaylorFan {
static var favoriteSong = "Shake it Off"
var name: String
var age: Int
}
let fan = TaylorFan(name: "James", age: 25)
print(TaylorFan.favoriteSong)
所以,Taylor Swift 的歌迷有属于他们的名字和年龄,但他们都有同样喜欢的歌曲。
因为静态方法属于 class 而不是 class 的实例,您不能使用它访问 class 的任何 non-static 属性.
我注意到 Swift
protocols
中的某些函数具有 static
关键字。但是,当您实现该功能时,您必须删除 static
关键字以使编译器满意。
public static func <(lhs: Self, rhs: Self) -> Bool
static
在上下文中是什么意思,它的目的是什么?
来自 Xcode 8 beta 4 发行说明:
Operators can be defined within types or extensions thereof. For example:
struct Foo: Equatable { let value: Int static func ==(lhs: Foo, rhs: Foo) -> Bool { return lhs.value == rhs.value } }
Such operators must be declared as
static
(or, within a class,class final
), and have the same signature as their global counterparts. As part of this change, operator requirements declared in protocols must also be explicitly declaredstatic
:protocol Equatable { static func ==(lhs: Self, rhs: Self) -> Bool }
静态属性和方法
Swift 允许您创建属于某个类型的属性和方法,而不是属于某个类型的实例。这有助于通过存储共享数据来有意义地组织数据。
Swift 调用这些共享属性 "static properties",您只需使用 static 关键字即可创建一个。完成后,您可以使用类型的全名访问 属性。这是一个简单的例子:
struct TaylorFan {
static var favoriteSong = "Shake it Off"
var name: String
var age: Int
}
let fan = TaylorFan(name: "James", age: 25)
print(TaylorFan.favoriteSong)
所以,Taylor Swift 的歌迷有属于他们的名字和年龄,但他们都有同样喜欢的歌曲。
因为静态方法属于 class 而不是 class 的实例,您不能使用它访问 class 的任何 non-static 属性.