Swift Protocol Extensions and Protocol-Oriented Programming
A protocol only states requirements without providing implementations, which brings flexibility but also means every conformer must write the same code again.
Protocol extensions solve this: they can add concrete implementations of methods, computed properties, and subscripts to a protocol.
Putting shared implementations in a protocol extension and letting different types conform as needed is what Swift calls protocol-oriented programming.
This article covers both its usage and the pitfalls it is easiest to fall into.
Protocol extensions provide default implementations
Use extension ProtocolName to add members to a protocol, written the same way as extending a normal type.
Implementations in the extension serve as default implementations, which conformers can use without writing their own.
Example
import Foundation
protocol RunoobGreetable
{
var name
:
String
{
get
}
func greet
(
)
String
}
// The protocol extension provides a default implementation
extension RunoobGreetable
{
func greet
(
)
String
{
return
"Hello, I am (name)"
}
}
struct
RunoobGuest
:
RunoobGreetable
{
var name
:
String
// Without writing greet(), the default implementation is used directly
}
struct
RunoobVip
:
RunoobGreetable
{
var name
:
String
// Provide your own implementation, overriding the default one
func greet
(
)
String
{
return
"VIP (name), welcome back"
}
}
(
RunoobGuest
(
name
:
"RUNOOB"
)
.
greet
(
)
)
(
RunoobVip
(
name
:
"Xiao Ming"
)
.
greet
(
)
)
Running result:
你好,我是 RUNOOB
贵宾 小明,欢迎回来
RunoobGuest provides only name, with greet() backed by the extension; RunoobVip writes its own greet(), so its own is used.
In this way, the protocol requires "you must have greet()", while the extension also solves "if you don't write it, we'll give you one".
Note:Default implementations turn a protocol requirement into an "optional implementation", and this comes at a cost. If a method should force each type to provide an implementation that fits its own semantics, do not give it a default implementation, or you risk leaving an inappropriate fallback.
Conditional conformance
Protocol extensions can also add conditional conformance to generic types: the type conforms to the protocol only when the generic parameter satisfies a certain condition.
The syntax is extension Type: Protocol where condition.
Example
import Foundation
protocol RunoobPayable
{
var amount
:
Double
{
get
}
func summary
(
)
String
}
struct
RunoobOrder
:
RunoobPayable
{
var amount
:
Double
func summary
(
)
String
{
return
"Order (amount) yuan"
}
}
// Conditional conformance: the array conforms to RunoobPayable only when Element itself is RunoobPayable
extension Array
:
RunoobPayable where Element
:
RunoobPayable
{
var amount
:
Double
{
return
reduce
(
0
)
{
$
0
$
1
.
amount
}
}
func summary
(
)
String
{
return
"Total (count) orders, summing to (amount) yuan"
}
}
let orders
=
[
RunoobOrder
(
amount
:
19.5
)
, RunoobOrder
(
amount
:
30.5
)
]
(
orders.
summary
(
)
)
Running result:
共 2 笔,合计 50.0 元
The condition is Element: RunoobPayable, so only arrays whose elements are themselves payable can call summary().
If the array elements are Int, the condition does not hold, so [Int] does not conform to RunoobPayable and the call is a compile-time error.
A protocol extension can also add a where Self: constraint, opening methods only to conformers that satisfy extra conditions.
Example
import Foundation
protocol RunoobScorable
{
var score
:
Int
{
get
}
}
// Extension with a Self constraint: only conformers that are also Equatable can use this method
extension RunoobScorable where Self
:
Equatable
{
func isBetterThan
(
_ other
:
Self
)
Bool
{
return
score
other.
score
}
}
struct
RunoobPlayer
:
RunoobScorable, Equatable
{
var name
:
String
var score
:
Int
}
let a
=
RunoobPlayer
(
name
:
"Xiao Ming"
, score
:
90
)
let b
=
RunoobPlayer
(
name
:
"Xiao Hong"
, score
:
85
)
(
a.
isBetterThan
(
b
)
)
// Protocol extensions can extend system protocols too
extension Collection
{
// Return the first element only when non-empty
var runoobFirstOrNil
:
Element
?
{
return
isEmpty
?
nil
:
first
}
}
(
[
10
,
20
,
30
]
.
runoobFirstOrNil
??
0
)
(
[
Int
]
(
)
.
runoobFirstOrNil
??
0
)
Running result:
true
10
0
The parameter of isBetterThan is Self, so it only makes sense when the conformer itself is comparable; that is the role of where Self: Equatable.
Extending a system protocol adds runoobFirstOrNil to Collection, so arrays, sets, and dictionaries can all use this property.
Protocol extension members do not use dynamic dispatch
This is the most famous pitfall of protocol extensions; the official documentation even uses a dedicated example to warn about its counterintuitive behavior.
In one sentence: members written only in the extension and not in the protocol body do not participate in dynamic dispatch.
| How the member is written | Called through a protocol type | Dispatch method |
|---|---|---|
| Declared in the protocol body + default implementation in the extension | Calls the conformer's implementation | Dynamic dispatch |
| Declared and implemented only in the extension | Always calls the implementation in the extension | Static dispatch |
First look at the "unexpected" case: the method is written only in the extension.
Example
import Foundation
protocol RunoobRunner
{
var name
:
String
{
get
}
}
extension RunoobRunner
{
// This method is written only in the extension, not a protocol requirement
func run
(
)
String
{
return
"(name) is jogging"
}
}
struct
RunoobAthlete
:
RunoobRunner
{
var name
:
String
func run
(
)
String
{
return
"(name) is sprinting"
}
}
let athlete
=
RunoobAthlete
(
name
:
"Xiao Ming"
)
(
athlete.
run
(
)
)
// The static type is RunoobAthlete, so its own implementation is called
let runner
:
any RunoobRunner
=
athlete
(
runner.
run
(
)
)
// The static type is the protocol, so the implementation in the extension is called
Running result:
小明 在冲刺
小明 在慢跑
For the same object, athlete.run() is "sprinting", but runner.run() becomes "jogging".
The reason is that run() is not a protocol requirement and has no entry in the protocol's witness table, so when called through any RunoobRunner only the static implementation in the extension can be used.
Now look at the correct approach: as long as run() is written into the protocol body, it is dynamically dispatched.
Example
import Foundation
protocol RunoobRunner2
{
var name
:
String
{
get
}
func run
(
)
String
// Declared as a protocol requirement
}
extension RunoobRunner2
{
func run
(
)
String
{
return
"(name) is jogging"
}
}
struct
RunoobSprinter
:
RunoobRunner2
{
var name
:
String
func run
(
)
String
{
return
"(name) is sprinting"
}
}
let sprinter
:
any RunoobRunner2
=
RunoobSprinter
(
name
:
"Xiao Hong"
)
(
sprinter.
run
(
)
)
// A protocol requirement uses dynamic dispatch, calling the type's own implementation
Running result:
小红 在冲刺
The only difference between the two approaches is whether func run() -> String appears in the protocol body, yet the results are completely different.
Note:If a member might later be customized by conformers and you will use it through a protocol type, you must write it into the protocol body. Writing it into the protocol body still allows a default implementation in the extension; the two do not conflict.
Trade-offs of protocol-oriented programming
The core idea of protocol-oriented programming is "define capabilities first, then compose capabilities", rather than building a class inheritance chain first.
It is especially friendly to value types: structs and enums cannot inherit, but they can conform to protocols and thus share implementations in protocol extensions.
However, it is no silver bullet; the table below can help you choose.
| Scenario | Recommended practices | Reason |
|---|---|---|
| Multiple types share the same implementation with no parent-child relationship | Protocol + protocol extension | Structs and enums can participate too, unconstrained by single inheritance |
| A genuine "is-a" relationship exists and superclass state needs to be reused | class inherits | Inheritance naturally carries stored properties and initializer chains |
| You care only about capabilities, not the concrete type | Protocol as a type or generic constraint | Decouples caller from implementer |
| A member needs polymorphic behavior and will be called through a protocol type | Write it into the protocol body | Avoid the static dispatch pitfall of protocol extensions |
| Pursuing extreme performance with frequent calls | Generic constraints rather than any | Generics allow static dispatch, while any needs boxing and table lookup |
Another benefit of protocol extensions is that they can add capabilities without modifying the original type; for example, add a convenience property to Collection and all collection types immediately gain it.
The cost is that if the protocol hierarchy is designed too deep, the call chain becomes hard to trace: whether a method uses the default implementation or the conformer's implementation requires looking back at the protocol body to determine.
The practical advice is: keep protocols small and focused, let each protocol describe one capability, then compose them with protocol composition.
Common questions
Below are some common questions about protocol extensions and protocol-oriented programming.
Can stored properties be declared in a protocol extension?
No. Extensions as a whole do not allow adding stored properties, and protocol extensions are no exception.
When "storage" is needed, either declare it in the conformer type or wrap it in a computed property.
When a default implementation conflicts with a protocol requirement, which takes precedence?
As long as the method is declared in the protocol body, the conformer's own implementation takes precedence and the default implementation only serves as a fallback.
If the method is declared only in the extension, then calls through a protocol type always use the extension's implementation and the conformer's implementation is ignored.
Does conditional conformance have side effects on existing types?
No. When the condition is not met, the type simply does not conform to the protocol, only meaning the relevant members cannot be called.
But be careful not to write two contradictory conditional conformances for the same type; the compiler will report a redundant conformance error.
What is the difference between a protocol extension and a normal type extension?
A normal type extension adds members to one concrete type, with impact limited to that type.
A protocol extension adds members to all conformers, with wider impact and a greater chance of name collisions with conformers' own members; think through the dispatch behavior when using it.