{

How to find the length or count of a Swift Enum with example


An enum is a group of case statements with fixed values.

This tutorial explains the length of a Swift Enum

enum WeekEnd {
    case Saturday
    case Sunday
}

print(WeekEnd.count) 

It throws an error main.swift:6:15: error: type 'WeekEnd' has no member 'count'. There is no method count in swift e

Swift Enum count cases

There are multiple ways to get the count of cases in a swift enumeration.

  • using CaseIterable protocol

add CaseIterable to enum and It provides an allCases function that returns a sequence of collection of enum cases. you can call the count property to return the length of an enum.

enum WeekEnd:CaseIterable  {
    case Saturday
    case Sunday
}

print(WeekEnd.allCases)  // [main.WeekEnd.Saturday, main.WeekEnd.Sunday]
print(WeekEnd.allCases.count)  // 2
  • add custom method count by implementing Int

Add static count method that returns Int value. Using a while loop iterates all cases and increments the count value by 1.

Here is an example

enum WeekEnd:Int   {
    case Saturday
    case Sunday
      static let count: Int = {
        var max: Int = 0
        while let _ = WeekEnd(rawValue: max) {
                max += 1 }
        return max
    }()

}

print(WeekEnd.count) //2

THE BEST NEWSLETTER ANYWHERE
Join 6,000 subscribers and get a daily digest of full stack tutorials delivered to your inbox directly.No spam ever. Unsubscribe any time.

Similar Posts
Subscribe
You'll get a notification every time a post gets published here.