![](/img/trans.png)
[英]Swift Unable to access static variables in class using type(of: Instance)
[英]Access static variables within class in Swift
ClassName.staticVaribale
是在类中访问静态变量的唯一方法吗? 我想要像self
这样的东西,但是为了上课。 像class.staticVariable
。
有两种方法可以从非静态属性/方法访问静态属性/方法:
如您的问题中所述,您可以在属性/方法名称前加上类型的前缀:
class MyClass { static let staticProperty = 0 func method() { print(MyClass.staticProperty) } }
Swift 2:你可以使用dynamicType
:
class MyClass { static let staticProperty = 0 func method() { print(self.dynamicType.staticProperty) } }
Swift 3:你可以使用type(of:)
(感谢@Sea Coast of Tibet):
class MyClass { static let staticProperty = 0 func method() { print(type(of: self).staticProperty) } }
如果你在静态属性/方法中,则不需要在静态属性/方法前加上任何东西:
class MyClass {
static let staticProperty = 0
static func staticMethod() {
print(staticProperty)
}
}
斯威夫特有一种方法可以让马塞尔的答案满足最挑剔的风格指导之神
class MyClass {
private typealias `Self` = MyClass
static let MyConst = 5
func printConst() {
print(Self.MyConst)
}
}
当你想要访问相关的类型声明时,这使得Self在协议中可用。 我不确定Swift 1,因为从未尝试过,但在Swift 2中它完美无缺
在未来的Swift 3版本(尚未发布)中,您可以使用Self
(是的,带有大写)来引用包含的类。 已接受提案,但该功能尚未实施。
例如:
struct CustomStruct {
static func staticMethod() { ... }
func instanceMethod() {
Self.staticMethod() // in the body of the type
}
}
资料来源: https : //github.com/apple/swift-evolution/blob/master/proposals/0068-universal-self.md
您可以通过定义自引用类型来解决此问题。
class MyClassWithALongName {
typealias CLASS = MyClassWithALongName
static let staticFoo = "foo"
func someInstanceMethod() -> String {
return CLASS.staticFoo
}
}
虽然风格导游的神可能不赞成。
看起来在Swift 4.2中,内部类和实例变量可以直接访问静态变量而不需要类名的前缀。 但是,您仍需要函数中的类名。
class MyClass {
static let staticProperty = 0
let property = staticProperty //YES
class Inner {
func method() {
print(staticProperty) //YES
}
}
func method() {
print(staticProperty) //NO
print(MyClass.staticProperty) //YES
}
}
我不喜欢这种情况下的typealias方式。 我的解决方法是:
class MyClass {
static let myStaticConst: Int = 1
var myStaticConst:Int {
return type(of: self).myStaticConst
}
func method() {
let i:Int = myStaticConst
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.