Protocols and extensions in Swift
State the requirement; share the implementation.
// A protocol states requirements; an extension supplies shared code.
protocol Signaling {
var callSign: String { get }
}
extension Signaling {
func hail() -> String { "\(callSign), \(callSign), race control" }
}
struct Yacht: Signaling {
let callSign: String
}
// Extensions also add to types you do not own.
extension String {
var flagged: String { "[FLAG] " + self }
}
let boat = Yacht(callSign: "Kestrel")
print(boat.hail())
print("black flag start".flagged)
How it works
protocol Signalingrequires one property.- An extension supplies
hail()to every conformer for free. extension Stringadds a property to a type you do not own.
Keywords and builtins used here
SignalingStringYachtextensionfuncgethailletprintprotocolstructvar
The run, in numbers
- Lines
- 20
- Characters to type
- 465
- Tokens
- 89
- Three-star pace
- 65 tpm
At the three-star pace of 65 tokens a minute, this run takes about 82 seconds.
Step 1 of 3 in Abstractions, step 19 of 27 in Language basics.