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 name2 var name: String { get }3}4 // Default implementations shared by all conforming types5extension Greetable { // Builds a greeting from name6 func greet() -> String {7 return "Hello, \(name)!"8 } // A second default method9 func wave() -> String {10 return "\(name) waves"11 }12}13 // User only provides name to conform14struct User: Greetable {15 var name: String16}17 18let user = User(name: "Alice")// Prints Hello, Alice!19print(user.greet())// Prints Alice waves20print(user.wave())Output
Hello, Alice! Alice waves
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