为什么 Swift 初始化器不能在其超类上调用便利初始化器?

Why can#39;t Swift initializers call convenience initializers on their superclass?(为什么 Swift 初始化器不能在其超类上调用便利初始化器?)
本文介绍了为什么 Swift 初始化器不能在其超类上调用便利初始化器?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑两个类:

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'
    }
}

我不明白为什么不允许这样做.最终,每个类的指定初始化程序都会使用它们需要的任何值来调用,那么为什么我需要在 Binit 中通过为 指定默认值来重复自己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 初始化器不能在其超类上调用便利初始化器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

Why local notification is not firing for UNCalendarNotificationTrigger(为什么没有为UNCalendarNotificationTrigger触发本地通知)
Pushing UIViewController above UITabBar(将UIView控制器推送到UITabBar上方)
Dropbox Files.download does not start when number of files in folder is gt; 1000(当文件夹中的文件数为1000时,Dropbox Files.Download不会启动)
appearance().setBackgroundImage Not Working On Custom Class(外观().setBackoundImage在自定义类上不起作用)
Show/Hide barButtonItem(显示/隐藏barButtonItem)
Didn#39;t find class quot;androidx.core.widget.DrawerLayoutquot;(未找到类androidx.core.widget.DrawerLayout(q;))