قالب وردپرس درنا توس
Home / IOS Development / # 320: Count Enum Cases with CaseIterable 🐤 – Little Bites of Cocoa

# 320: Count Enum Cases with CaseIterable 🐤 – Little Bites of Cocoa



Subjects

Topics

Back in Bite # 292 we looked at Sourcery and how we could use it to add practical features like count to our Swift enums. Sourcery is still as good, but Swift 4.2 actually removes the need to use it in this … case . 🤭 Let's have a look.

We start with the problem we are trying to solve. Let's imagine a simple

enum

: 

 enum    Romskip    {
    case    tantiveIV 
    case    ghost 
    case    falke 
 ]} 

We often add in the list of cases in enum as new spaceships and we would like to display the number of spaceship in our app. We can expand our enum and add a count property:

 extension    Romskip    {
    static    var    count  : .. [1
9659000] Int
{ Return ([ TantiveIV Ghost Falcon ] as [ ] Romskip ]) . count } }

Maintenance of this code will not be fun. When we add new enum cases, we must never forget to update also this expansion feature implementation as well. Yuck.

In Swift 4.2 we can solve this quite elegantly by pushing the extension and instead adjust our enum to the new CaseIterable protocol:

 enum    Romskip 
    Romskip 
    ] CaseIterable    {
    case    tantiveIV 
    case    ghost 
    case    falcon 
} 

Now we can access the number of spaceships anywhere in Our Code:

  print   (  Romskip .   allCases .   count ) 

Tidy!

We use counter for simplicity here, but as the name suggests, allCases state property like CaseIterable to our enums course us to look through us enums things.

It's all for today, do you have a question or idea for a piece? Send it to hello@littlebitesofcocoa.com.


Source link