关于Swift中重写类属性的困惑 [英] Confusion Regarding Overriding Class Properties in Swift
问题描述
我已经阅读了Swift文档并在这里进行了搜索,但是我仍然不确定如何实现一个类层次结构,其中每个子类都为继承的静态属性设置自定义值.即:
I have read the Swift docs and searched here, but I still am not sure about how to implement a class hierarchy where each subclass sets custom value for an inherited static property; that is:
- 基类定义了静态属性:所有实例共享相同的值.
- 子类覆盖静态属性:所有实例共享相同的值,与基类的形式不同.
可以存储财产吗?
此外,我应该如何从实例方法(无论特定的类)中访问属性的值,并每次都获取正确的值?以下代码可以工作吗?
Also, How should I access the value of the property from within an instance method (regardless of the particular class), and get the correct value everytime? will the following code work?
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)
}
推荐答案
您是如此接近,除了不能覆盖子类中的static
属性,这就是class
属性,这意味着它必须是计算属性-Swift缺少存储的class
属性.
You are so close to being there, except that you can't override a static
property in a subclass — that is what it means to be static
. So you'd have to use a class
property, and that means it will have to be a computed property — Swift lacks stored class
properties.
所以:
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"}
}
让我们对其进行测试:
ClassA().doYourThing() // A
ClassB().doYourThing() // B
这篇关于关于Swift中重写类属性的困惑的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!