Nic*_*ari 9 inheritance static properties swift
我已经阅读过Swift文档并在这里进行了搜索,但我仍然不确定如何实现一个类层次结构,其中每个子类为继承的静态属性设置自定义值; 那是:
该物业可以存储吗?
另外,我应该如何从实例方法中访问属性的值(无论特定的类),并且每次都获得正确的值?以下代码是否有效?
class BaseClass
{
// To be overridden by subclasses:
static var myStaticProperty = "Hello"
func useTheStaticProperty()
{
// Should yield the value of the overridden property
// when executed on instances of a subclass:
let propertyValue = self.dynamicType.myStaticProperty
// (do something with the value)
}
Run Code Online (Sandbox Code Playgroud)
mat*_*att 19
你是如此接近,除了你不能覆盖static子类中的属性 - 这就是它的意思static.所以你必须使用一个class属性,这意味着它必须是一个计算属性 - Swift缺少存储的class属性.
所以:
class ClassA {
class var thing : String {return "A"}
func doYourThing() {
print(type(of:self).thing)
}
}
class ClassB : ClassA {
override class var thing : String {return "B"}
}
Run Code Online (Sandbox Code Playgroud)
让我们测试一下:
ClassA().doYourThing() // A
ClassB().doYourThing() // B
Run Code Online (Sandbox Code Playgroud)