Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why do I get "Static member '...' cannot be used on instance of type '...'" error?

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'

Screenshot

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?

like image 813
Sergey Kalinichenko Avatar asked Mar 28 '16 21:03

Sergey Kalinichenko


1 Answers

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)])
        //         ^^^^^^^^
    }
}
like image 136
Sergey Kalinichenko Avatar answered Oct 18 '22 03:10

Sergey Kalinichenko