typestar

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

  1. protocol Signaling requires one property.
  2. An extension supplies hail() to every conformer for free.
  3. extension String adds a property to a type you do not own.

Keywords and builtins used here

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.

Type this snippet

Step 1 of 3 in Abstractions, step 19 of 27 in Language basics.

← Previous Next →