Swift 5: Useful Protocols to Write Like a Pro

Swiftos
Geek Culture
Published in
4 min readFeb 27, 2021

--

Photo by Danielle MacInnes on Unsplash

Hi iOS Developers,

I’m guessing we have all experienced the pain of spending a lot of time implementing a function, only to realize later that Swift has a built-in function that does the same thing. In this article, I will talk about a few useful protocols that can save you much time and take your code to the next level.

1. CaseIterable

The CaseIterable protocol allows you to retrieve all the values of the type. Let’s take a look at an example:

Without CaseIterable:

enum City {
case new_york
case bei_jing
case vancouver
....
}
let cities: [City] = [.new_york, .bei_jing, .vancouver, ....]

In this example, when we want to retrieve all the cities from the City enum, we would have to type them out manually. Imagine that if this enum has hundreds of thousands of cities, it would be a nightmare to do that.

With CaseIterable:

enum City: CaseIterable {
case new_york
case bei_jing
case vancouver
....
}
let cities = City.allCases

With the allCases property provided by the CaseIterable protocol, we can retrieve an array of all the cases of City. This can save a significant amount of…

--

--

Swiftos
Geek Culture

I publish short iOS development tutorials on a weekly basis. For all content, head over to: https://www.patreon.com/Swiftos