das*_*ght 10 static compiler-errors swift
以下是在实例方法中直接使用静态成员:
public struct RankSet {
private let rankSet : UInt8
static let counts : [UInt8] = [
0, 1, 1, 2, 1, 2, 2, 3, 1, 2, 2, 3, 2, 3, 3, 4,
... // More of the same
4, 5, 5, 6, 5, 6, 6, 7, 5, 6, 6, 7, 6, 7, 7, 8
]
public var count : Int {
get {
// The error is on the following line
return Int(counts[Int(rankSet)])
}
}
}
Run Code Online (Sandbox Code Playgroud)
Swift产生以下错误:
静态成员
'counts'
不能在类型的实例上使用'RankSet'
由于静态成员在我的类的所有实例之间共享,因此所有实例成员(包括count
)都应该有权访问该counts
成员.这里发生了什么?
das*_*ght 26
错误消息具有误导性:可以从任何具有适当可见性的代码访问静态成员,其中包括实例方法.
但是,Swift不提供从实例方法访问静态成员的短名称 - 这是许多其他编程语言的常见功能.这是导致上述错误的原因.
Swift坚持完全限定静态成员的名称,如下所示:
public var count : Int {
get {
return Int(RankSet.counts[Int(rankSet)])
// ^^^^^^^^
}
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
9326 次 |
最近记录: |