简体   繁体   中英

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. Does swift have an alias to do this?

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 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. The advantage of type(of:) and Self over just saying the name is that they are polymorphic.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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