如果能够使用类似于"自我;作为别名访问封闭的Struct或Class的静态变量。swift有化名吗?
例如:
struct MyStruct {
static let variable = "Hello"
func accessVariable() {
MyStruct.variable // This works
self.variable // I'd like to be able to do this.
}
}
或类别:
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!
}
}
有三种方法:
MyStruct.variable
type(of:self).variable
Self.variable
Self
关键字是Swift最近的一项创新,可能是您的首选。type(of:)
和Self
的优点在于它们是多态的。