0

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!
    }
}
1
  • 2
    Self.variable Commented Dec 5, 2020 at 17:20

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.