Protocol Extensions: Default Behavior for Free
Protocol extensions give conforming types default functionality "for free," like a standard toolkit with every blueprint. Use them to add common behavior to your protocols or even extend system types.
Why it exists
Protocols define a contract of methods and properties, but they don't provide the actual code. Before protocol extensions, every single type conforming to a protocol had to write its own implementation for every requirement, leading to significant code duplication for common functionality.
The mental model
Think of a protocol as a blueprint for a car, specifying it must have an engine and wheels. A protocol extension is like a factory-standard engine and a set of all-season tires that come with the blueprint. Any car model built from this blueprint gets these standard parts automatically. A custom sports car model can still choose to install its own high-performance engine, which would be used instead of the standard one.
How it works
You declare an extension on a protocol itself, like extension MyProtocol { ... }. Inside this block, you can write concrete implementations for the methods or computed properties defined in the protocol's requirements. Any type that conforms to MyProtocol now automatically has access to these default implementations. If the conforming type provides its own implementation for a method, the type's specific version is called at runtime, overriding the default.
When to use it
Protocol extensions are a cornerstone of Protocol-Oriented Programming in Swift. Use them to: first, provide default behavior for your own protocols, drastically reducing boilerplate for conforming types. Second, add new functionality to existing protocols, including standard library types like Collection or Codable. For example, you could add a helper method to all Encodable types that returns their JSON Data representation.
When not to use it
Do not use a protocol extension to add new requirements to a protocol; extensions are for adding behavior, while the protocol definition itself is for defining the contract. You also cannot add stored properties in an extension; only computed properties are allowed. Be cautious with methods defined only in the extension (not in the protocol requirements), as their dispatch behavior can lead to unexpected results.
One canonical example
A powerful use is extending Swift's Collection protocol to add functionality to all arrays, sets, and dictionaries. For example, you can add a method to get a safe element at an index, returning nil if the index is out of bounds. extension Collection {
subscript(safe index: Index) -> Element? {return indices.contains(index) ? self[index] : nil
}
}
Now any array, like let letters = ["a", "b"], can safely access an element with letters[safe: 2], which returns nil instead of crashing.
Interview question
Consider a protocol with a default method implementation provided by a protocol extension. If a type conforming to this protocol also implements that same method, which version will be executed?
- a.The default implementation from the protocol extension will always be executed, ignoring the type's version.
- b.The choice of implementation depends on whether the method is called from within the type or from an external context.
- c.A compilation error will occur because a method cannot have two implementations.
- d.The type's specific implementation will be executed, taking precedence over the default.Correct
Why? this is the answer
The card explicitly states: "If the conforming type provides its own implementation for a method, the type's specific version is called at runtime, overriding the default." This allows for customization while still providing a fallback. Option A is incorrect because the type's specific implementation takes precedence.
Just read this? Test yourself on what you have been reading.
Read the original → docs.swift.org
Put your scrolling time to good use
Learn one idea, try a quiz and save useful cards for revision. Tezvyn makes it easy to learn and stay current in your tech field, a few minutes at a time.
The iPhone app is on the way
We are building it. Until it lands, nothing here is held back from you: every interview card, your saved cards, streaks and the job board all work in Safari, plus hundreds of free practice quizzes of thirty questions each. Sign in and it all carries over to the app the day it arrives.
Want it as an icon? Tap Share at the bottom of Safari, then Add to Home Screen. It opens full screen and the cards you have read stay available offline.
We are hiring for this. Open roles that interview on swift — each one lists the topics its interview covers.
See open roles