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 property
2 var description: String { get }
3}
4
// Methods in a protocol extension are available to all conforming types
5extension Describable {
6 func printDescription() {
// Can use description because every conforming type has it
7 print("Description: \(description)")
8 }
9}
10
// A stored property satisfies the { get } requirement
11struct Item: Describable {
12 var description: String
13}
14
15let item = Item(description: "A useful item")
// Item did not write this method; it comes from the extension
// Prints Description: A useful item
16item.printDescription()

Output

Description: A useful item
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.

  • :× 5
  • (× 5
  • )× 5
  • {× 5
  • }× 5
  • "× 4
  • .× 1
  • \× 1
  • =× 1

More Swift examples at level 4

← Swift typing practice