Member-only story
Understanding the “Some” and “Any” Keywords in Swift 5.7
No more confusion!

The some
and any
keywords are not new in Swift. The some
keyword was introduced in Swift 5.1 whereas the any
keyword was introduced in Swift 5.6. In Swift 5.7, Apple makes another great improvement on both of these keywords. We can now use both of these keywords in the function’s parameter position!
This improvement not only made the generic functions look a lot cleaner, but also unlocked some exciting new ways to write generic code in Swift. Spoiler alert — we can now say goodbye to the following error message:
protocol can only be used as a generic constraint because it has Self or associated type requirements
Want to know more? Read on!
First Things First
Before getting into the details, let’s define the protocol we will be using throughout this article.
After that, we will define a Car
and a Bus
struct that conforms to the Vehicle
protocol and each of them will require different kinds of fuels. Here’s the code:
Notice that the fillGasTank(with:)
function’s parameter data type of Car
and Bus
are not the same, Car
requires Gasoline
whereas Bus
requires Diesel
. That is why we need to define an associated type called FuelType
in our Vehicle
protocol.
With that out of the way, let’s dive right into the details, shall we?