Here is a straightforward use of a static member inside an instance method:
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)])
}
}
}
Swift produces the following error:
Static member
'counts'
cannot be used on instance of type'RankSet'
Since static members are shared among all instances of my class, all instance members, including count
, should have access to the counts
member. What is going on here?
The error message is misleading: static members can be accessed from any piece of code that has proper visibility to them, which includes instance methods.
However, Swift does not provide a short name access to static members from instance methods - a common feature of many other programming languages. This is what is causing the error above.
Swift insists on fully qualifying names of static members, as follows:
public var count : Int {
get {
return Int(RankSet.counts[Int(rankSet)])
// ^^^^^^^^
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With