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

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

    So it comes in handy when you don't need to specify each and every property for a class. So for instance, if I want to create all adventures with starting HP value of 100, I would use this following convenience init and just add in a name. This is going to cut down on the code a lot.

    class Adventure { 
    
    // Instance Properties
    
        var name: String
        var hp: Int
        let maxHealth: Int = 100
    
        // Optionals
    
        var specialMove: String?
    
        init(name: String, hp: Int) {
    
            self.name = name
            self.hp = hp
        }
    
        convenience init(name: String){
            self.init(name: name, hp: 100)
        }
    }
    

提交回复
热议问题