Protocol Definition in Swift

Level 4272 keystrokes

The Drawable protocol requires a read-only description property and a draw() method. Circle meets both with a computed property and a method, and draw prints Drawing Circle(r=5.0).

Swift code

1protocol Drawable {
// { get } means conforming types must at least allow reading it
2 var description: String { get }
// Method requirement, no body
3 func draw()
4}
5
// Circle declares conformance after the colon
6struct Circle: Drawable {
7 var radius: Double
// A computed property satisfies the description requirement
8 var description: String { return "Circle(r=\(radius))" }
// Implements draw() using description
9 func draw() { print("Drawing \(description)") }
10}
11
// The variable's type is the protocol; 5 becomes the Double 5.0
12let shape: Drawable = Circle(radius: 5)
// Calls Circle's draw(): prints Drawing Circle(r=5.0)
13shape.draw()

Output

Drawing Circle(r=5.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.

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

More Swift examples at level 4

← Swift typing practice