What can live in a protocol? What can live in an extension?
Predict first
Does this compile?
protocol Named {
var name = "anonymous"
}
- Yes
- No
Mental model. A protocol is a job description — duties only, no office. An extension is the office where you actually do the work.
A protocol declares requirements: methods, properties (get/set), initializers, subscripts, associated types, and primary associated types. Since Swift 5.7 it can also have protocol-level generic constraints via primary associated types.
An extension can add methods, computed properties, nested types, protocol conformances, default implementations, and where-constrained members. It cannot add stored properties — the closest hack is Objective-C associated objects, which you should treat as a code smell.
A protocol declares requirements only. Default values and stored storage belong in conforming types; default behaviour goes in an extension as a computed property or method.
Common traps
- Trying to add a stored property in an extension. Not possible. Use a wrapper, a subclass, or restructure the type.
- Assuming extension members are requirements. They are not, unless the protocol also declares them — this is the bug in Q22.
They might follow up with
- Can a protocol inherit from another protocol? Yes, class-style composition:
protocol B: A { }. - Can a protocol require a
staticmember? Yes, andstaticrequirements can be satisfied by class or static members.
Related questions
- 1.3.2 What is protocol-oriented programming, and when does it fail?
- 1.3.3 Protocol extension vs inheritance for default behaviour — what are the tradeoffs?
What is protocol-oriented programming, and when does it fail? →