なんとかするから、なんとかなる

エンジニア関係のことを書きます

Swift 4.2 How to get a all values of enum

Introduction

This article shows how to use "CaseIterable" protocol which introduced in Swift4.2.

This protocol can provede all values of enum type. So, I do not need to implement such a property any more.

Before Swift4.2

In Swift4.1 or earlier, When I need an all values of enum types for case sentence or something.

I always implmented this property as below.

enum MyEnum {
    case one
    case two
    case three

    static let allValues = [MyEnum.one, MyEnum.two, MyEnum.three]
}

Using this propery, I could get a number of values of enum or get all values in loop sentence.

In Swift4.2

Now, I can use a CaseIterable Protocol.

I just need to declear the protocol when enum property define as below.

enum MyEnum: CaseIterable {
    case one
    case two
    case three
 }

It is very simple way to get an all values or number of values in enum as below.

// Get number of values in enum
MyEnum.allCases.count

// Get an all value in loop sentence
for item in MyEnum.allCases {
    // Do something with item
}

## Wrap up! This protocol give me an great solution for using enum. Let's use it and never imple such a propery any more!

Reference

CaseIterable - Swift Standard Library | Apple Developer Documentation