Logo for tanaschita.com

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 Item
func 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.

Image of books
News from tanaschita.com: I'm now offering sponsorship
By publishing a new article on different iOS topics every week, tanaschita.com is constantly growing in the developer community and may provide a great audience for you as a sponsor. Click here to learn more.

Newsletter

Receive a monthly newsletter about the latest articles and tips.

Image of a reading marmot

Related tags

Written by

Articles with related topics

Latest articles and tips