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

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

    Where convenience initializers beat setting default parameter values

    For me, convenience initializers are useful if there is more to do than simply set a default value for a class property.

    Class implementation with designated init()

    Otherwise, I would simply set the default value in the init definition, e.g.:

    class Animal {
    
        var race: String // enum might be better but I am using string for simplicity
        var name: String
        var legCount: Int
    
        init(race: String = "Dog", name: String, legCount: Int = 4) {
            self.race = race
            self.name = name
            self.legCount = legCount // will be 4 by default
        }
    }
    

    Class extension with convenience init()

    However, there might be more to do than simply set a default value, and that is where convenience initializers come in handy:

    extension Animal {
        convenience init(race: String, name: String) {
            var legs: Int
    
            if race == "Dog" {
                legs = 4
            } else if race == "Spider" {
                legs = 8
            } else {
                fatalError("Race \(race) needs to be implemented!!")
            }
    
            // will initialize legCount automatically with correct number of legs if race is implemented
            self.init(race: race, name: name, legCount: legs)
        }
    }
    

    Usage examples

    // default init with all default values used
    let myFirstDog = Animal(name: "Bello")
    
    // convenience init for Spider as race
    let mySpider = Animal(race: "Spider", name: "Itzy")
    
    // default init with all parameters set by user
    let myOctopus = Animal(race: "Octopus", name: "Octocat", legCount: 16)
    
    // convenience init with Fatal error: Race AlienSpecies needs to be implemented!!
    let myFault = Animal(race: "AlienSpecies", name: "HelloEarth")
    

提交回复
热议问题