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: String
3 var calories: Int
4
// Designated initializer: sets every stored property
5 init(name: String, calories: Int) {
6 self.name = name
7 self.calories = calories
8 }
9
// Convenience init: calories defaults to 0
10 convenience init(name: String) {
// Delegates to the designated initializer
11 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 arguments
19let a = Food(name: "Apple", calories: 95)
20let b = Food(name: "Water")
21let c = Food()
// Prints Apple: 95, Water: 0, Unknown: 0
22print("\(a.name): \(a.calories), \(b.name): \(b.calories), \(c.name): \(c.calories)")

Output

Apple: 95, Water: 0, Unknown: 0
Practice typing this code

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

More Swift examples at level 4

← Swift typing practice