美文网首页
Swift 子类初始化方法总结

Swift 子类初始化方法总结

作者: 悦思 | 来源:发表于2017-01-12 15:20 被阅读81次

    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只能纵向调用

    Paste_Image.png

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

    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 子类初始化方法总结

          本文链接:https://www.haomeiwen.com/subject/gwgdbttx.html