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.

Sponsorship logo
Using Proxyman to inspect network traffic
Proxyman is a native debugging proxy that can act as a man-in-the-middle between your application and web server. You can use its powerful toolkit to inspect network calls and debug your application on Mac, iOS Simulator, or remote devices effortlessly.
CLICK TO LEARN MORE

Newsletter

Image of a reading marmot
Subscribe

Like to support my work?

Say hi

Related tags

Articles with related topics

generics and protocols

swift

swiftui

ios

Understanding opaque types in Swift

Learn how to use opaque return types in Swift and SwiftUI.

07 Feb 2022 · 3 min read

Latest articles and tips

© 2022 tanaschita.com

Privacy policy

Impressum