Reputation: 23
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
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