是否是ClassName.staticVaribale在类中访问静态变量的唯一方法?我想要类似的东西self,但是为了上课.喜欢class.staticVariable.
ABa*_*ith 103
有两种方法可以从非静态属性/方法访问静态属性/方法:
如您的问题中所述,您可以在属性/方法名称前加上类型的前缀:
class MyClass {
static let staticProperty = 0
func method() {
print(MyClass.staticProperty)
}
}
Run Code Online (Sandbox Code Playgroud)Swift 2:你可以使用dynamicType:
class MyClass {
static let staticProperty = 0
func method() {
print(self.dynamicType.staticProperty)
}
}
Run Code Online (Sandbox Code Playgroud)
斯威夫特3:你可以使用type(of:)(感谢@Sea Coast of Tibet):
class MyClass {
static let staticProperty = 0
func method() {
print(type(of: self).staticProperty)
}
}
Run Code Online (Sandbox Code Playgroud)如果你在静态属性/方法中,则不需要在静态属性/方法前加上任何东西:
class MyClass {
static let staticProperty = 0
static func staticMethod() {
print(staticProperty)
}
}
Run Code Online (Sandbox Code Playgroud)
Sla*_*off 33
斯威夫特有一种方法可以让马塞尔的答案满足最挑剔的风格指导之神
class MyClass {
private typealias `Self` = MyClass
static let MyConst = 5
func printConst() {
print(Self.MyConst)
}
}
Run Code Online (Sandbox Code Playgroud)
当你想要访问相关的类型声明时,这使得Self在协议中可用.我不确定Swift 1,因为从未尝试过,但在Swift 2中它完美无缺
在未来的Swift 3版本(尚未发布)中,您可以使用Self(是的,有资本)来引用包含的类.已接受提案,但该功能尚未实施.
例如:
struct CustomStruct {
static func staticMethod() { ... }
func instanceMethod() {
Self.staticMethod() // in the body of the type
}
}
Run Code Online (Sandbox Code Playgroud)
资料来源:https://github.com/apple/swift-evolution/blob/master/proposals/0068-universal-self.md
在Swift 5.1中可以很好地解决此问题,您可以通过访问它
Self.yourConstant
Run Code Online (Sandbox Code Playgroud)
参考:https : //github.com/apple/swift-evolution/blob/master/proposals/0068-universal-self.md
| 归档时间: |
|
| 查看次数: |
28684 次 |
| 最近记录: |