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 it2 var description: String { get } // Method requirement, no body3 func draw()4}5 // Circle declares conformance after the colon6struct Circle: Drawable {7 var radius: Double // A computed property satisfies the description requirement8 var description: String { return "Circle(r=\(radius))" } // Implements draw() using description9 func draw() { print("Drawing \(description)") }10}11 // The variable's type is the protocol; 5 becomes the Double 5.012let 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. 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