为什么我不能在类型为'...'的实例上使用“静态成员'...'”;错误? [英] Why do I get "Static member '...' cannot be used on instance of type '...'" error?

查看:76
本文介绍了为什么我不能在类型为'...'的实例上使用“静态成员'...'”;错误?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是在实例方法中直接使用静态成员的方法:

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会产生以下错误:

Swift produces the following error:


静态成员'counts'不能用于类型<$ c的实例$ c>'RankSet'

由于静态成员是共享的在我班的所有实例中,所有实例成员,包括 count ,都应有权访问 counts 成员。

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.

但是,Swift不提供从实例方法对静态成员的短名称访问,这是许多其他编程语言的共同功能。这就是导致上述错误的原因。

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坚持使用静态成员的完全限定名称,如下所示:

Swift insists on fully qualifying names of static members, as follows:

public var count : Int {
    get {
        return Int(RankSet.counts[Int(rankSet)])
        //         ^^^^^^^^
    }
}

这篇关于为什么我不能在类型为'...'的实例上使用“静态成员'...'”;错误?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆