在Swift中访问类中的静态变量

use*_*411 55 swift

是否是ClassName.staticVaribale在类中访问静态变量的唯一方法?我想要类似的东西self,但是为了上课.喜欢class.staticVariable.

ABa*_*ith 103

有两种方法可以从非静态属性/方法访问静态属性/方法:

  1. 如您的问题中所述,您可以在属性/方法名称前加上类型的前缀:

    class MyClass {
        static let staticProperty = 0
    
        func method() {
            print(MyClass.staticProperty)
        }
    }
    
    Run Code Online (Sandbox Code Playgroud)
  2. Swift 2:你可以使用dynamicType:

    class MyClass {
        static let staticProperty = 0
    
        func method() {
            print(self.dynamicType.staticProperty)
        }
    }
    
    Run Code Online (Sandbox Code Playgroud)

    斯威夫特3:你可以使用type(of:)(感谢@Sea Coast of Tibet):

    class MyClass {
        static let staticProperty = 0
    
        func method() {
            print(type(of: self).staticProperty)
        }
    }
    
    Run Code Online (Sandbox Code Playgroud)

如果你在静态属性/方法中,则不需要在静态属性/方法前加上任何东西:

class MyClass {
    static let staticProperty = 0

    static func staticMethod() {
        print(staticProperty)
    }
}
Run Code Online (Sandbox Code Playgroud)

  • 所以如果我们在同一个类中,但在实例方法中,我们需要编写那个类名吗?这对我来说似乎很奇怪,因为编译器肯定能推断出实例的类.我只是不想输入相同的类名.如果我可以像class.staticVaribale那样输入,那会很棒,但事实并非如此吗? (4认同)
  • 在Swift 3中,#2将是`type(of:self).staticProperty` (4认同)

Sla*_*off 33

斯威夫特有一种方法可以让马塞尔的答案满足最挑剔的风格指导之神

class MyClass {

    private typealias `Self` = MyClass

    static let MyConst = 5

    func printConst() {
        print(Self.MyConst)
    }
}
Run Code Online (Sandbox Code Playgroud)

当你想要访问相关的类型声明时,这使得Self在协议中可用.我不确定Swift 1,因为从未尝试过,但在Swift 2中它完美无缺

  • 这是最好的解决方案.有一个[接受的提议](https://github.com/apple/swift-evolution/blob/master/proposals/0068-universal-self.md)无论如何都要将它添加到语言中.它会略有不同,因为`Self`意味着动态类型,因此如果被访问的成员被覆盖,它将使用被覆盖的值.基本上这是一个最好的解决方案作为一个止损,直到这是语言的正式部分. (4认同)

edw*_*dmp 6

在未来的Swift 3版本(尚未发布)中,您可以使用Self(是的,有资本)来引用包含的类.已接受提案,但该功能尚未实施.

例如:

struct CustomStruct {          
 static func staticMethod() { ... } 

 func instanceMethod() {          
   Self.staticMethod() // in the body of the type          
 }          
}
Run Code Online (Sandbox Code Playgroud)

资料来源:https://github.com/apple/swift-evolution/blob/master/proposals/0068-universal-self.md


Xco*_*OOB 5

在Swift 5.1中可以很好地解决此问题,您可以通过访问它

Self.yourConstant
Run Code Online (Sandbox Code Playgroud)

参考:https : //github.com/apple/swift-evolution/blob/master/proposals/0068-universal-self.md