在初始化期间使用覆盖的静态属性 [英] Using an overriden static property during initialization
问题描述
我想创建一个具有静态属性的类,子类可以覆盖该属性,该属性将用于初始化实例。到目前为止,我已经尝试完成以下操作:
I would like to create a class with a static property that subclasses can override, which would be used to initialize instances. So far, I've tried to accomplish this like this:
import Cocoa
class A: NSObject {
class var staticProperty: String {
return "A"
}
var property: String = A.staticProperty
}
class B: A {
override class var staticProperty: String {
return "B"
}
}
这不起作用,因为 B()。property
仍返回 A 。如何更改此代码,以使
属性
包含子类指定的值?任何帮助将不胜感激!
This does not work, since B().property
still returns "A"
. How could I change this code so that property
contains the value specified by the subclass? Any help would be appreciated!
编辑
我想初始化属性
的值为 staticProperty
,因此它也可能像这样:
Edit
I would like to initialize property
with the value of staticProperty
, so this could also look like this:
var property: SomeClass = SomeClass(A.staticProperty)
但是,此初始化仍应将 A
用于A类,将 B
用于B类。
But then, this initialization should still use "A"
for class A, and "B"
for class B.
编辑2(在@RakeshaShastri发表评论之后)
对于我的特定用例,我需要属性
来
编辑3
总之,我正在尝试构建一个领域模型类,它与其他模型之间有许多关系。对于这些模型(它们非常相似),我试图创建一个包含共享功能的超类,其中还包括反向关系。因此,我想拥有一个静态属性,该属性包含第一个模型中其他任何一个模型的密钥,然后使用该密钥名称初始化LinkingObjects属性。由于Realm不允许延迟或计算,因此我不能在这里使用这些功能。
Edit 3 In short, I'm trying to build a Realm model class which has a few to-many relationships to other models. For these models (which are quite similar), I'm trying to create a superclass which contains the shared functionality, amongst which is also the inverse relationship. Therefore, I want to have a static property which contains the key in the first model to either of the other models, and then initialize a LinkingObjects property using this key name. Since Realm does not allow this to be lazy or computed, I cannot use these functionalities here.
推荐答案
如果您继承自NSObject,为什么?不使用它吗?
If you inherit from NSObject why not using it ?
import Cocoa
class A: NSObject {
var property: String
public override init() {
let str = type(of: self).perform(#selector(getter: type(of: self).staticProperty))?.takeUnretainedValue() as! String
property = str
}
@objc class var staticProperty: String {
return "A"
}
}
class B: A {
override class var staticProperty: String {
return "B"
}
}
这篇关于在初始化期间使用覆盖的静态属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!