Why do I get “Static member '…' cannot be used on instance of type '…'” error?

后端 未结 1 2076
难免孤独
难免孤独 2021-02-20 08:32

Here is a straightforward use of a static member inside an instance method:

public struct RankSet {
    private let rankSet : UInt8
    static let counts : [UInt         


        
相关标签:
1条回答
  • 2021-02-20 08:55

    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)])
            //         ^^^^^^^^
        }
    }
    
    0 讨论(0)
提交回复
热议问题