简体   繁体   English

如何在不使用类型名称的情况下引用 static Swift 结构或 class 变量?

[英]How to reference static Swift Struct or class variables without using the Type name?

It would be nice to be able to use something similar to "self" as an alias to access the enclosing Struct or Class's static variables.如果能够使用类似于“self”的东西作为别名来访问封闭的 Struct 或 Class 的 static 变量,那就太好了。 Does swift have an alias to do this? swift 是否有别名来执行此操作?

For example:例如:

struct MyStruct {
    static let variable = "Hello"
    
    func accessVariable() {
        MyStruct.variable // This works

        self.variable // I'd like to be able to do this.
    }
}

Or class:或 class:

class MyClass {
    static let variable = "Hello"
    
    func accessVariable() {
        MyClass.variable // This works

        self.variable // I'd like to be able to do this.
        class.variable // Or this would be nice too!
    }
}

There are three ways:有以下三种方式:

    MyStruct.variable
    type(of:self).variable
    Self.variable

The Self keyword is a relatively recent Swift innovation, and is probably your preferred choice here. Self关键字是一个相对较新的 Swift 创新,在这里可能是您的首选。 The advantage of type(of:) and Self over just saying the name is that they are polymorphic. type(of:)Self的优势在于它们是多态的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM