如何在不使用Type名称的情况下引用静态Swift Struct或类变量



如果能够使用类似于"自我;作为别名访问封闭的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的优点在于它们是多态的。

最新更新