Protocol Extension in Swift

Level 4289 keystrokes

A protocol extension gives every Greetable type two ready-made methods, greet() and wave(). User only declares name, yet it can call both: Hello, Alice! and Alice waves.

Swift code

1protocol Greetable {
// The only requirement: a readable name
2 var name: String { get }
3}
4
// Default implementations shared by all conforming types
5extension Greetable {
// Builds a greeting from name
6 func greet() -> String {
7 return "Hello, \(name)!"
8 }
// A second default method
9 func wave() -> String {
10 return "\(name) waves"
11 }
12}
13
// User only provides name to conform
14struct User: Greetable {
15 var name: String
16}
17
18let user = User(name: "Alice")
// Prints Hello, Alice!
19print(user.greet())
// Prints Alice waves
20print(user.wave())

Output

Hello, Alice!
Alice waves
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.

  • (× 9
  • )× 9
  • "× 6
  • {× 6
  • }× 6
  • :× 4
  • -× 2
  • .× 2
  • \× 2
  • >× 2

More Swift examples at level 4

← Swift typing practice