Discover CaseIterable


You’re more of a video kind of person? I’ve got you covered! Here’s a video with the same content than this article 🍿


Have you ever heard of the protocol CaseIterable?

When you use enums, this protocol can be very useful!

Let’s take the example of this simple enum:

If we make this enum conform to the protocol CaseIterable, then the compiler will automatically generate a static property called allCases, which is an array that contains all the cases of the enum:

That’s pretty a cool addition which can be very useful, typically to write tests that cover each possible case!

That’s all for this article, I hope you’ve enjoyed it!

Here’s the code if you want to experiment with it:

import Foundation

enum Direction: CaseIterable {
    case north
    case south
    case east
    case west
}

Direction.allCases // [.north, .south, .east, .west]
Previous
Previous

Here’s my second (traditional) newsletter 📮

Next
Next

This is my first (traditional) newsletter 📮