问题描述
考虑两个类:
class A {
var x: Int
init(x: Int) {
self.x = x
}
convenience init() {
self.init(x: 0)
}
}
class B: A {
init() {
super.init() // Error: Must call a designated initializer of the superclass 'A'
}
}
我不明白为什么不允许这样做.最终,每个类的指定初始化程序都会使用它们需要的任何值来调用,那么为什么我需要在 B 的 init 中通过为 指定默认值来重复自己x 再次,当 A 中的方便 init 可以正常工作?
I don't see why this isn't allowed. Ultimately, each class's designated initializer is called with any values they need, so why do I need to repeat myself in B's init by specifying a default value for x again, when the convenience init in A will do just fine?
推荐答案
这是 Swift Programming Guide 中指定的Initializer Chaining"规则的第 1 条,内容如下:
This is Rule 1 of the "Initializer Chaining" rules as specified in the Swift Programming Guide, which reads:
规则 1:指定初始化程序必须从他们的直接超类.
Rule 1: Designated initializers must call a designated initializer from their immediate superclass.
https://developer.apple.com/库/内容/文档/Swift/Conceptual/Swift_Programming_Language/Initialization.html
强调我的.指定初始化器不能调用便利初始化器.
Emphasis mine. Designated initializers cannot call convenience initializers.
有一个图表与规则一起展示了允许哪些初始化程序方向":
There is a diagram that goes along with the rules to demonstrate what initializer "directions" are allowed:
这篇关于为什么 Swift 初始化器不能在其超类上调用便利初始化器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!


大气响应式网络建站服务公司织梦模板
高端大气html5设计公司网站源码
织梦dede网页模板下载素材销售下载站平台(带会员中心带筛选)
财税代理公司注册代理记账网站织梦模板(带手机端)
成人高考自考在职研究生教育机构网站源码(带手机端)
高端HTML5响应式企业集团通用类网站织梦模板(自适应手机端)