Swift调用类函数来自超类函数中的相应子类

编程入门 行业动态 更新时间:2024-10-24 04:39:29
本文介绍了Swift调用类函数来自超类函数中的相应子类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我想在超类中实现 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调用类函数来自超类函数中的相应子类

本文发布于:2023-11-26 20:18:10,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1635046.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:函数   子类   Swift

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!