What is the difference between convenience init vs init in swift, explicit examples better

后端 未结 10 1965
醉梦人生
醉梦人生 2021-01-30 08:18

I am having troubles to understand the difference between both, or the purpose of the convenience init.

10条回答
  •  太阳男子
    2021-01-30 08:47

    All answers are sounds good but, lets understand it with an simple example

    class X{                                     
       var temp1
       init(a: Int){
            self.temp1 = a
           }
    

    Now, we know a class can inherit another class, So

    class Z: X{                                     
       var temp2
       init(a: Int, b: Int){
            self.temp2 = b
            super.init(a: a)
           }
    

    Now, in this case while creating instance for class Z, you will have to provide both values 'a' and 'b'.

    let z = Z(a: 1, b: 2)
    

    But, what if you only want to pass b's value and want rest to take default value for others, then in that case you need to initialise other values a default value. But wait how?, for that U need to set it well before in the class only.

    //This is inside the class Z, so consider it inside class Z's declaration
    convenience init(b: Int){
        self.init(a: 0, b: b)
    }
    convenience init(){
        self.init(a: 0, b: 0)
    }
    

    And now, you can create class Z's instances with providing some, all or none values for the variables.

    let z1 = Z(b: 2)
    let z2 = Z()
    

提交回复
热议问题