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

后端 未结 10 1951
醉梦人生
醉梦人生 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:50

    It makes sense if your use case is to call an initializer in another initializer in the same class.

    Try to do this in playground

    class Player {
        let name: String
        let level: Int
    
        init(name: String, level: Int) {
            self.name = name
            self.level = level
        }
        
        init(name: String) {
            self.init(name: name, level: 0) //<- Call the initializer above?
    
            //Sorry you can't do that. How about adding a convenience keyword?
        }
    }
    
    Player(name:"LoseALot")
    
    

    With convenience keyword

    class Player {
        let name: String
        let level: Int
    
        init(name: String, level: Int) {
            self.name = name
            self.level = level
        }
        
        //Add the convenience keyword
        convenience init(name: String) {
            self.init(name: name, level: 0) //Yes! I am now allowed to call my fellow initializer!
        }
    }
    

提交回复
热议问题