What Are Some and Any in Swift?

Explore Protocols and Generics More

Tolga Taner
2 min readOct 24, 2023
Photo by Irina on Unsplash

Some and any are keywords that are used before protocol variable declaration to specify its type existential or opaque. At first, as we iOS developers, we met some keyword in SwiftUI View body variable definition with Swift 5.1. After that, we met any keyword with Swift 5.6.

Let’s start with an example that contains some part of known architecture VIP and how we implement them.

Think about a protocol that represents LiveMatch as the top level protocol conforms PeriodicLiveMatch like voleyball matches and MinutedLiveMatch like football, basketball.

If we want to create a LiveMatch array that contains both conformed type, we can’t access the specific property of MinutedLiveMatch, PeriodicLiveMatch. The compiler tell us that all we know that there is a LiveMatch list.

For showing our view models on UI purpose, we need to create a protocol with an associatedtype to implement generic approach and two ViewModels to be conformed.

and then two presenters to decide which live match is so the business logic.

Instead of doing this, thanks to some, any keyword we can modify returning type as LiveMatchViewModel.

By doing this, the compiler tells us,

  • I read a list of PeriodicLiveMatch, thanks to matching of associated type you can return a list of LiveMatch.
  • With some keyword, the function always returns same type. There is no an another LiveMatch conformed type. Therefore, we can compare them each other. This refers opaque type.

Another changing with these keywords in Swift, all of them are doing the same.

  • With any keyword, the function can return any LiveMatch conformed type. Therefore, we can modify the second function.

To understand any keyword better and why it is existential, let us think about creating a protocol instance inside a type scope. The compiler doesn’t know the memory usage. It means using any can cause the performance overheading. If you want to deep diving performance issues you can check dynamically dispatching and statically dispatching topics.

That’s all for now. I think, we will use these keywords more day by day because of the restriction of the property that is existential or not type error in Swift 6.0.

Thanks for reading!

--

--