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
Preparing for a technical iOS job interview - updated for iOS 17
Check out my book on preparing for a technical iOS job interview with over 200 questions & answers. Test your knowledge on iOS topics such as Swift, SwiftUI, Combine, HTTP Networking, Authentication, SwiftData & Core Data, Concurrency with async/await, Security, Automated Testing, Machine Learning and more.
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

© 2024 tanaschita.com

Privacy policy

Impressum