Protocol Definition in Swift

Level 4347 keystrokes

The Drawable protocol requires a draw() method, and Circle and Square each implement it. Both are stored in one [Drawable] array, and each draw call runs the matching type's implementation.

Swift code

// A protocol lists requirements without implementing them
1protocol Drawable {
// Every conforming type must provide draw()
2 func draw()
3}
4
// Circle conforms to Drawable
5struct Circle: Drawable {
6 var radius: Double
// Its own implementation of draw()
7 func draw() {
8 print("Drawing circle with radius \(radius)")
9 }
10}
11
// Square conforms to Drawable with a different implementation
12struct Square: Drawable {
13 var side: Double
14 func draw() {
15 print("Drawing square with side \(side)")
16 }
17}
18
// Using the protocol as a type lets one array hold both structs; 5 and 3 become Double
19let shapes: [Drawable] = [Circle(radius: 5), Square(side: 3)]
// Each element runs its own draw(): radius 5.0, then side 3.0
20for shape in shapes { shape.draw() }

Output

Drawing circle with radius 5.0
Drawing square with side 3.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.

  • (× 10
  • )× 10
  • :× 7
  • {× 6
  • }× 6
  • "× 4
  • [× 2
  • ]× 2
  • \× 2
  • ,× 1

More Swift examples at level 4

← Swift typing practice