“必需"是什么意思?Swift 中的关键字是什么意思?

编程入门 行业动态 更新时间:2024-10-05 11:14:38
本文介绍了“必需"是什么意思?Swift 中的关键字是什么意思?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

举个例子:

class A { var num: Int required init(num: Int) { self.num = num } } class B: A { func haveFun() { println("Woo hoo!") } }

我已将A 的init 函数标记为required.这到底是什么意思?我在子类 B 中完全省略了它,编译器根本没有抱怨.那怎么需要呢?

I've marked A's init function as required. What exactly does this mean? I completely omitted it in the subclass B and the compiler doesn't complain at all. How is it required, then?

推荐答案

参见 "自动初始化继承":

规则 1 如果你的子类没有定义任何指定的初始化器,它自动继承其所有超类指定的初始值设定项.

Rule 1 If your subclass doesn’t define any designated initializers, it automatically inherits all of its superclass designated initializers.

规则 2 如果您的子类提供了其所有超类指定的初始值设定项——或者通过继承它们规则 1,或通过提供自定义实现作为其一部分定义——然后它自动继承所有超类便利初始化器.

Rule 2 If your subclass provides an implementation of all of its superclass designated initializers—either by inheriting them as per rule 1, or by providing a custom implementation as part of its definition—then it automatically inherits all of the superclass convenience initializers.

在您的示例中,子类 B 本身没有定义任何初始化程序,因此它继承 A 的所有初始化器,包括所需的初始化器.如果 B 只定义了便利初始值设定项,同样如此(现已针对 Swift 2 进行更新):

In your example, the subclass B does not define any initializers on its own, therefore it inherits all initializers from A, including the required initializer. The same is true if B defines only convenience initializers (now updated for Swift 2):

class B: A { convenience init(str : String) { self.init(num: Int(str)!) } func haveFun() { print("Woo hoo!") } }

但是如果子类定义了任何指定的(=不方便的)初始化器,那么它不再继承超类初始值设定项.特别是所需的初始化程序不是继承的,所以这不会编译:

But if the subclass defines any designated (= non-convenience) initializer then it does not inherit the superclass initializers anymore. In particular the required initializer is not inherited, so this does not compile:

class C: A { init(str : String) { super.init(num: Int(str)!) } func haveFun() { print("Woo hoo!") } } // error: 'required' initializer 'init(num:)' must be provided by subclass of 'A'

如果从 A 的 init 方法中删除 required 然后类 C也可以编译.

If you remove the required from A's init method then class C compiles as well.

更多推荐

“必需"是什么意思?Swift 中的关键字是什么意思?

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

发布评论

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

>www.elefans.com

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