A team adopted a rule: every service gets a protocol. Six months later the project had NetworkClientProtocol, ArticleServiceProtocol, ArticleRepositoryProtocol, and a mock for each. The folders were symmetrical. The test target compiled quickly.
Then the backend moved the article feed from REST to GraphQL, and the pull request touched forty files, views included.
The project had many interfaces and almost no boundaries. You can have either without the other, and the forty-file diff is what the first without the second looks like. Turning on Swift 6 tends to produce the same diff from another direction: the compiler flags one protocol at an isolation boundary, and the change ripples through every consumer that never needed to know.
The question worth asking about any protocol has nothing to do with how many types conform to it. It is this: which decisions do its consumers no longer need to know about?
The protocol that hides nothing
This is the kind of protocol that produces the forty-file diff:
import Foundation
protocol APIClientProtocol {
var session: URLSession { get }
var refreshToken: String? { get set }
func send(_ request: URLRequest) async throws -> (Data, HTTPURLResponse)
func paginated(_ request: URLRequest, page: Int) async throws -> (Data, HTTPURLResponse)
}Every requirement is a fact about the current implementation: it uses URLSession, it authenticates with a refresh token, it speaks HTTP, it paginates by page number. A feature that depends on this protocol builds URLRequest values, reads status codes, and decodes JSON. It is coupled to all four decisions, and extracting the protocol from the class changed none of that. This is an implementation with a second name.
The mock makes it worse, quietly. A test that stubs send to return hand-written JSON asserts that the feature can parse the JSON its author imagined. It keeps passing after the real server changes shape.
Start from what the consumer needs
A reading screen needs articles. It does not need pagination headers, token state, or a session delegate. So the contract is written from the feature’s side and named for the capability:
import Foundation
struct Article: Identifiable, Equatable, Sendable {
let id: UUID
let title: String
}
/// Loads the articles for the reader's home feed.
///
/// - Returns articles newest first; the order is stable between calls
/// when the underlying data has not changed.
/// - An empty array is a successful result: the feed has no articles.
/// - Throws `CancellationError` if the calling task is cancelled.
/// Cancellation abandons the request; it never returns partial data.
protocol ArticleLoading: Sendable {
func load() async throws -> [Article]
}
struct ArticleFeed<Loader: ArticleLoading>: Sendable {
let loader: Loader
func refresh() async throws -> [Article] {
try await loader.load()
}
}Article is a domain value the feature owns, with no Codable conformance and no knowledge of JSON keys. The REST adapter decodes its own DTO and maps it. When GraphQL arrives, a second adapter maps a generated type to the same Article. The diff is one new file and one line in the composition root.
The doc comment is the part people skip, and it is the actual contract. func load() async throws -> [Article] says nothing about ordering, about whether a cached result is acceptable, about what empty means, or about what cancellation does. Two implementations can satisfy the signature and differ on every one of those, and the screen will behave differently depending on which is injected. If a behavior matters to the consumer, write it beside the requirement. Then a mock that ignores it is visibly wrong.
One implementation is enough to justify this protocol, provided the boundary really contains a change. Ten implementations do not justify the first.
Not every seam needs a protocol
A pipeline with one decoder and one image optimizer can hold two concrete values. Adding DecoderProtocol and OptimizerProtocol buys two more files to keep in sync and contains no decision.
When the seam is a single operation with no shared state, a closure is the smaller tool:
struct FeedAction: Sendable {
let load: @Sendable () async throws -> [Article]
func callAsFunction() async throws -> [Article] {
try await load()
}
}A SwiftUI preview can pass FeedAction { [Article(id: UUID(), title: "Preview")] } without declaring a type. A protocol earns its place when the operations share state or lifetime (open, read, close), when associated types express a relationship (a parser and its output), or when the capability carries isolation rules worth naming.
“Always use the simplest thing” is the same kind of rule as “always use a protocol.” A public package API may deserve a protocol before a second implementation exists, because adding one later breaks clients. The reason should be a concrete compatibility or change requirement. “We might need it” is not one.
Generic, opaque, or existential
Once there is a protocol, Swift offers three ways to use it, and each makes a different promise.
// Generic: the caller chooses the type; the relationship is preserved.
func firstTitle<L: ArticleLoading>(from loader: L) async throws -> String? {
try await loader.load().first?.title
}
// Opaque: the implementation chooses one type and hides which.
func makeDefaultLoader() -> some ArticleLoading {
StaticLoader(articles: [])
}
// Existential: the stored type can vary at runtime.
struct FeedRegistry {
var loaders: [String: any ArticleLoading] = [:]
}
struct StaticLoader: ArticleLoading {
let articles: [Article]
func load() async throws -> [Article] { articles }
}| Form | Who picks the concrete type | What the caller can rely on |
|---|---|---|
Generic parameter <L: P> | The caller | The same type flows through the whole call; associated types line up |
Opaque result some P | The implementation | Always the same hidden type, so identity and associated types are stable |
Existential any P | Whoever stored the value, at runtime | Only the protocol’s requirements; the type may differ per value |
A dictionary of heterogeneous loaders needs any. A parser whose output must match what the next stage consumes wants generics. A factory that should be free to change its return type later wants some.
On performance: an existential stores small values inline, in a three-word buffer, boxes larger ones on the heap, and dispatches through a witness table. Generic code can be specialized by the optimizer, which removes that indirection and grows the binary. Whether either matters in your app is a question for Instruments, on a Release build, on the real call path. Architecture bent around an imagined dispatch cost does more harm than the dispatch, and a feed that awaits the network is not limited by a witness-table lookup.
Where customization actually happens
This example belongs in every protocol review, because it is a behavioral bug, not a speed question:
protocol Playback {
func play()
}
extension Playback {
func stop() -> String { "default extension" }
}
struct VideoPlayback: Playback {
func play() {}
func stop() -> String { "concrete type" }
}
func demonstrateDispatch() -> (concrete: String, existential: String) {
let concrete = VideoPlayback()
let abstract: any Playback = concrete
return (concrete.stop(), abstract.stop())
// ("concrete type", "default extension")
}stop() is declared only in the extension, so it is not a requirement, so it has no entry in the witness table. Through the concrete type the compiler sees VideoPlayback.stop. Through any Playback, or a generic <P: Playback>, it can see only the extension. The same object answers differently depending on the static type of the variable that holds it.
If conformers are meant to customize stop, declare it in the protocol and keep the extension as the default. If they are not, the conformer’s method shadows rather than overrides, and it deserves a different name.
Isolation is part of the contract
A protocol silent about isolation leaves every conformer and caller to discover it at compile time, usually under migration pressure. State it:
@MainActor
protocol StatusDisplaying: AnyObject, Sendable {
func show(_ message: String)
}
func report(_ message: String, to display: any StatusDisplaying) async {
await display.show(message)
}The annotation tells conformers they may touch UI state freely and tells callers on other executors that they must await.
The Sendable refinement does real work. A @MainActor class is implicitly Sendable, but any StatusDisplaying is not unless the protocol says so. Remove it and report stops compiling in Swift 6 mode: a nonisolated function would be sending a non-Sendable existential to the main actor. swiftc -typecheck accepts that version. The error comes from region-based isolation analysis later in the build, so you only see it when you compile for real, which is worth knowing the next time a quick typecheck reassures you.
The harder case is the reverse: a nonisolated protocol you do not own, and a @MainActor class that should conform. Before Swift 6.2 the choices were nonisolated witnesses with a manual hop back, or @preconcurrency. Swift 6.2 added isolated conformances (SE-0470), which let the conformance itself carry the isolation:
protocol Describable {
func describe() -> String
}
@MainActor
final class StatusBanner {
var text = "Idle"
}
extension StatusBanner: @MainActor Describable {
func describe() -> String { text }
}The compiler then prevents the conformance from being used off the main actor, which is the guarantee you wanted in the first place.
Three keywords get confused in these discussions. Sendable says a value may cross an isolation boundary. async says a function may suspend. An actor annotation says where code runs. None makes a remote operation atomic. And a protocol that promises Sendable more broadly than its conformers can deliver pushes them toward @unchecked Sendable, which silences the one check that would have caught the race.
Abstractions that keep the platform’s hard rules visible
A good boundary survives the changes that do not matter and still exposes the constraints that do.
On tvOS, a pure function that picks the preferred index after a reload is easy to test and worth extracting. It cannot promise that a particular view receives focus; the focus engine decides. A FocusManaging abstraction that pretends otherwise will pass its tests and fail on the device.
On watchOS, a workout summary formatter can vary freely. Background execution limits and energy cost cannot be abstracted behind it, and code written against a “platform-independent” service layer that omits them will be written as if they did not exist.
On iPadOS and macOS, a document exporter should not care whether the document sits in a split view or its own window. It may well need a stable document revision to export from while the user keeps typing. That requirement belongs in the contract.
When a layer is described as platform-independent, check whether it is independent of the platform’s details or merely silent about its hardest rules. For a shared core, make the independence enforceable: dependency direction between targets, package access for what crosses targets inside one package, and a check on which frameworks each target may import.
Test the contract, then the adapters
If the documented behavior is the contract, it can be executed. One function, run against every implementation, the fake included:
struct ContractViolation: Error, Equatable {
let rule: String
}
func verifyArticleLoadingContract(_ loader: some ArticleLoading) async throws {
let first = try await loader.load()
let second = try await loader.load()
guard first.map(\.id) == second.map(\.id) else {
throw ContractViolation(rule: "order is stable between calls")
}
guard Set(first.map(\.id)).count == first.count else {
throw ContractViolation(rule: "identifiers are unique")
}
let cancelled = Task {
try await loader.load()
}
cancelled.cancel()
if let partial = try? await cancelled.value, partial != first {
throw ContractViolation(rule: "cancellation never yields partial data")
}
}Call it from a test for the REST adapter against a local stub server, from a test for the GraphQL adapter, and from a test for the in-memory fake that powers previews. A fake that passes the same suite as the real adapters is a fake whose green tests mean something.
Adapter tests stay close to the external system. No mock can verify that your Decodable types match what the server sends, that a save is really transactional, or that a delegate callback arrives on the queue you assumed. Those need the real decoder, the real store, and recorded or live responses.
The removal question
For each protocol in the module, ask what would be lost if it were deleted and its single conformer used directly.
Sometimes the answer is concrete: the feature module would import the networking module; previews would need a server; the GraphQL migration would touch every screen; the type relationship between parser and renderer would go unchecked. Keep those.
Sometimes the answer is “we always use protocols.” Delete those. Each is a file to maintain, a mock to update, and a false signal to the next engineer that a boundary exists.
What to ask of your own code
- Which decision does this protocol keep away from its consumers?
- Are ordering, emptiness, caching, and cancellation written beside the requirement, or only in the implementation?
- Is a method that conformers customize declared in the protocol, or only in an extension?
- Does the protocol state its isolation, and does its
Sendablepromise match what conformers can honestly deliver? - Does the fake pass the same contract suite as the real adapters?
A concrete type commits you to an implementation. A protocol commits you to requirements and the semantics you wrote down. A generic signature commits you to a type relationship, an existential to runtime variation, an isolation annotation to an executor. Architecture is choosing which of those commitments the product needs, and keeping their consequences where a reviewer can see them.
References
- The Swift Programming Language: Protocols
- The Swift Programming Language: Opaque and Boxed Protocol Types
- SE-0335: Introduce existential
any - SE-0470: Global-actor isolated conformances
Related editions
- Edition 13 · From Prototype to Client Delivery
- Edition 29 · From Swift to GraphQL: Understanding the Work Behind a Request
- Edition 32 · Swift Testing: Test Behavior, Not Implementation
If this edition sharpened your next review, you can buy me a coffee.