Swift 子类初始化方法总结

1 文档说 有三条Rule:
“Rule 1
A designated initializer must call a designated initializer from its immediate superclass.

Rule 2
A convenience initializer must call another initializer from the same class.

Rule 3
A convenience initializer must ultimately call a designated initializer.”

其实就是说 convennience只能横向调用,designed只能纵向调用

Swift 子类初始化方法总结_第1张图片
Paste_Image.png

2 关于自定义初始化 是区别于convennience & designed的,如果你的自定义初始化 前面加convennience,就需要调用同级的初始化,没有修饰的话就需要调用super的designed。

Swift 子类初始化方法总结_第2张图片
Paste_Image.png

参考下面代码

“class RecipeIngredient: Food {
    var quantity: Int
    init(name: String, quantity: Int) {
        self.quantity = quantity
        super.init(name: name)
    }
    override convenience init(name: String) {
        self.init(name: name, quantity: 1)
    }
}”

你可能感兴趣的:(Swift 子类初始化方法总结)