Swift protocols: requirements, extension defaults and a sensor example.
In one line
Keeping only what callers need to know and hiding the rest. In Swift a protocol states what a type must do, and an extension hands shared behavior to every conforming type at once.
Why you need it
Write report code separately for each sensor and the formats drift apart. The screen must call a different function per sensor, and every new sensor adds screen code.
Let Sensor require a name, a unit and read(), and write report() once in an extension. A new sensor then only says how to read its value, and the screen knows nothing but any Sensor.
Everyday picture
Think of a wall socket. The socket (the protocol) only says "plugs of this shape get power". A hair dryer or a charger works as long as the plug fits. The overload cut-off on a power strip (a default implementation in an extension) protects every device plugged in, automatically.
Example code
main.swift · 53 lines
let sensors: [anySensor] = [Thermometer(room: "kitchen"), StepCounter(steps: [1200, 3400, 800])]for s in sensors {print(s.report())}let alerts = sensors.filter { $0.isAlert }.map { $0.name }print("alerts: \(alerts)")protocolSensor {var name: String { get }var unit: String { get }var isAlert: Bool { get }funcread() -> Double}extensionSensor {var isAlert: Bool {false }funcreport() -> String {let value = read()return"\(name): \(value) \(unit)" }}structThermometer: Sensor {let room: Stringlet unit = "C"var name: String {"temp(\(room))" }funcread() -> Double {let raw = 735returnDouble(raw) / 30 }}structStepCounter: Sensor {let steps: [Int]let name = "steps"let unit = "k"var isAlert: Bool { steps.reduce(0, +) < 6000 }funcread() -> Double {let total = steps.reduce(0, +)returnDouble(total) / 1000 }}
Swift code does not run on this page. Save your edited code as main.swift on your own computer, compile it with swiftc and run it.
protocol vs class inheritance
protocol + extension
class inheritance
Works for structs and enums
O
X
Can use several
O
X
Stored properties
X
O
Default implementations
O
O
Passes init down
X
O
Create an object from it alone
X
O
A protocol states only what a type must be able to do; default implementations sit in an extension. When the shared part needs a lot of stored state, combine it with class inheritance.
When to use it
Several types do the same job in different ways (read())
You want shared behavior for structs and enums too; class inheritance works only for classes.
Behavior is mostly the same with a few exceptions: a default in an extension, own versions only where needed
Anything that must vary per type belongs in the protocol body as a requirement. A method that exists only in an extension is not overridden, as mistake 1 shows.
The Swift standard library works this way too: conform to Equatable or Comparable and you get == and sorting.
Common mistakes
Overriding a method that exists only in an extension
When label() lives only in the extension and not in the protocol, a call through any Gadget ignores the real type and uses the extension version, so the fan also says gadget. List methods that should vary per type in the protocol to make them requirements.
Wrong
let gadgets: [anyGadget] = [Lamp(), Fan()]for g in gadgets {print(g.label())}protocolGadget {var watts: Int { get }}extensionGadget {funclabel() -> String {"gadget \(watts)W" }}structLamp: Gadget {let watts = 9}structFan: Gadget {let watts = 40funclabel() -> String {"fan \(watts)W" }}
When you run itgadget 9W
gadget 40W
Fixed
let gadgets: [anyGadget] = [Lamp(), Fan()]for g in gadgets {print(g.label())}protocolGadget {var watts: Int { get }funclabel() -> String}extensionGadget {funclabel() -> String {"gadget \(watts)W" }}structLamp: Gadget {let watts = 9}structFan: Gadget {let watts = 40funclabel() -> String {"fan \(watts)W" }}
When you run itgadget 9W
fan 40W
Missing a requirement
Declaring conformance to Sensor means providing every requirement that has no default (read()). isAlert may be left out because the extension supplies a default. The Double 1013 prints as 1013.0.
Wrong
structBarometer: Sensor {let name = "air"let unit = "hPa"}
What the Swift compiler sayserror: type 'Barometer' does not conform to protocol 'Sensor'
Fixed
print(Barometer().report())structBarometer: Sensor {let name = "air"let unit = "hPa"funcread() -> Double {1013 }}
When you run itair: 1013.0 hPa
Creating an object straight from a protocol
A protocol is only a contract and cannot be instantiated. Create a conforming type (Thermometer) and give the receiving variable the type any Sensor.
Wrong
let sensor = Sensor()
What the Swift compiler sayserror: 'any Sensor' cannot be constructed because it has no accessible initializers
Fixed
let sensor: anySensor = Thermometer(room: "hall")print(sensor.report())
When you run ittemp(hall): 24.5 C
Check yourself
Question 1
Thermometer has no report(). What does this line print?
print(Thermometer(room: "lab").report())
Show the answer
Answer: 1. temp(lab): 24.5 C It uses the default report() from extension Sensor. The name comes from the computed property name on the thermometer: temp(lab).
Question 2
What is isAlert on a thermometer?
print(Thermometer(room: "lab").isAlert)
Show the answer
Answer: 2. false The thermometer does not define isAlert, so it gets the default from the extension: false.
Questions people ask
Does Swift have abstract classes?
No. Protocols fill that role: list the job in a protocol and put shared behavior in an extension as a default implementation. When stored properties must be shared too, combine it with ordinary class inheritance.
Why is an extension-only method not overridden?
Only requirements listed in the protocol body are chosen by the real type. A method that exists only in an extension is chosen by the variable type, so through any the extension version runs.
What is protocol-oriented programming?
Splitting jobs into several small protocols instead of an inheritance tree, and giving default behavior through extensions. A big plus is that structs and enums can take part.