我想在超类中实现 init(coder aDecoder:NSCoder!),并通过调用特定子类中的类方法在所有子类中使用它运行时的超类。
I would like to implement init(coder aDecoder: NSCoder!) in a superclass, and use it in all subclasses by calling a class method on the particular subclass in the superclass at runtime.
class func dummyDict() -> NSDictionary init(coder aDecoder: NSCoder!) { for(key,value) in self.class.dummyDict(){ -------------------- ^ | | Get this from the corresponding subclass at runtime! NSLog("encoding \(value) for key \(key)") } }来自 MySuperClass 的子类是否可以访问类函数 dummyDict ()在运行时?
Is it possible that subclasses from MySuperClass access the class function dummyDict() at runtime ?
推荐答案我想我抓住了你的意思。您创建一个 Base 类,实现初始化程序和类(静态)函数:
I think I caught what you mean. You create a Base class, implementing an initializer and a class (static) function:
class Base { class func dummyDict() -> Dictionary<String, String> { return ["base1": "val1"] } init() { for (key, value) in self.dynamicType.dummyDict() { println("encoding \(value) for key \(key)") } } }接下来,您要创建子类,并使用初始化程序调用 dummyDict 方法的重写版本。您只需要覆盖该方法:
Next you want to create subclasses, and have the initializer to call an overridden version of the dummyDict method. You simply have to override that method:
class Subclass1 : Base { override class func dummyDict() -> Dictionary<String, String> { return ["subclass1": "sub1"] } }现在,当您创建 Subclass1 的实例时,打印的是:
Now, when you create an instance of Subclass1, what's printed is:
encoding sub1 for key subclass1这是预期的输出。
注意初始化程序中的 for 循环使用 self.dynamicType.dummyDict()而不是 Base.dummyDict()。后者总是调用 Base 类中定义的类方法,而前者在继承自 Base
Note the for loop in the initializer is using self.dynamicType.dummyDict() rather than Base.dummyDict(). The latter always calls the class method defined in the Base class, whereas the former calls it in the scope of the actual class inherited from Base
更多推荐
Swift调用类函数来自超类函数中的相应子类
发布评论