Understanding opaque types and protocols with associatedtype in Swift
Learn how to leverage the some keyword for working with protocols with associated types.
06 Jan 2025 · 2 min read
Protocols with associatedtype or Self requirements often bring challenges when used as parameters or return types in Swift. Historically, developers needed to rely on generics to work around these limitations, leading to sometimes complex code.
This article will show how to use opaque types to simplify interactions with such protocols.

As an example, let's look at a protocol with an associated type.
protocol Store {associatedtype Itemfunc persist(item: Item)}
Because of the associatedtype, the protocol does not have a fully determined concrete type until we provide a specific implementation. This makes it impossible to use the protocol directly as a parameter or return type without triggering a compile-time error.
For example, writing the following function results in an error:
func cleanup(store: Store) {// Error: Protocol 'Store' can only be used as a generic constraint because it has Self or associated type requirements.}
To work around this, we could define the function as a generic:
func cleanup<T: Store>(store: T) {}
While this works, it introduces complexity. By using opaque types, we can simplify:
func cleanup(store: some Store) {// Simplified function declaration.}
The opaque declaration is basically syntactic sugar for the equivalent generic code. The compiler will automatically infer the concrete parameter type without needing us to write the generic code.



Newsletter
Like to support my work?
Say hi
Related tags
Articles with related topics
Latest articles and tips



