Convenience Initializer in Swift
Level 4424 keystrokes
A convenience init must call another initializer of the same class with self.init. init() delegates to init(name:), which delegates to the designated init, filling in default values. It prints Apple: 95, Water: 0, Unknown: 0.
Swift code
1class Food {2 var name: String3 var calories: Int4 // Designated initializer: sets every stored property5 init(name: String, calories: Int) {6 self.name = name7 self.calories = calories8 }9 // Convenience init: calories defaults to 010 convenience init(name: String) { // Delegates to the designated initializer11 self.init(name: name, calories: 0)12 }13 // No arguments: delegates to the other convenience init with "Unknown"14 convenience init() {15 self.init(name: "Unknown")16 }17}18 // Each call picks the initializer that matches its arguments19let a = Food(name: "Apple", calories: 95)20let b = Food(name: "Water")21let c = Food()// Prints Apple: 95, Water: 0, Unknown: 022print("\(a.name): \(a.calories), \(b.name): \(b.calories), \(c.name): \(c.calories)")Output
Apple: 95, Water: 0, Unknown: 0
Practice typing this code. Results are not recorded in the rankings.
Symbols in this code
The symbols you type in this Swift code and how often they appear.
(× 15)× 15:× 14.× 10"× 8\× 6,× 5=× 5{× 4}× 4