zephyern
zephyern

Reputation: 23

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!
    }
}

Upvotes: 0

Views: 330

Answers (1)

matt
matt

Reputation: 535511

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.

Upvotes: 1

Related Questions