Protocol Extension in Swift
Level 4273 keystrokes
An extension adds printDescription() with an implementation to every Describable type. Item only provides description and still gets the method, printing Description: A useful item.
Swift code
1protocol Describable { // Requires a readable description property2 var description: String { get }3}4 // Methods in a protocol extension are available to all conforming types5extension Describable {6 func printDescription() { // Can use description because every conforming type has it7 print("Description: \(description)")8 }9}10 // A stored property satisfies the { get } requirement11struct Item: Describable {12 var description: String13}14 15let item = Item(description: "A useful item")// Item did not write this method; it comes from the extension// Prints Description: A useful item16item.printDescription()Output
Description: A useful item
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.
:× 5(× 5)× 5{× 5}× 5"× 4.× 1\× 1=× 1