Understanding the some keyword when working with generic protocols in Swift 5.7
Learn about opaque parameter declarations introduced at WWDC22.
13 Jun 2022 · 2 min read
Introduced at WWDC22, Swift now allows us to use the some keyword when referencing generic protocols as parameters.
As an example, let's look at a protocol with an associated type.
protocol Store {associatedtype Itemfunc persist(item: Item)}
Before Swift 5.7, we had to write the following to use the Store protocol as a parameter:
func cleanup<T: Store>(store: T) {}
Trying to reference the protocol directly with
func cleanup(store: Store) {}
would get us the error Protocol Store can only be used as a generic constraint because it has Self or associated type requirements.
With Swift 5.7, we are now allowed to use the some keyword to solve this problem.
func cleanup(store: some Store) {}
The opaque declaration is basically syntactic sugar for the equivalent generic code. Just like with using the some keyword to define opaque return types, the compiler will automatically infer the concrete parameter type without needing us to write the generic code.

Newsletter
Related tags
Written by
Articles with related topics
Latest articles and tips