How to print all the cases of an enum in Swift

Overview

An enum or enumeration is a user-defined data type with data that are related. With the CaseIterable method, we can print all the cases of an enum in Swift. We have to create the enum with this method and then print the values with the allCases method.

Syntax

enum EnumName:type, CaseIterable{
case value
}
// print all cases
print(EnumName.allCases)
The syntax that enables us to print the cases of an enum in Swift

Parameters

  • type: This is the data type specified for our enum.
  • EnumName: This represents the name we want to give our enum.
  • value: This is the value for each case.

Code

import Swift
// create some enumerations
enum Colors:Int, CaseIterable {
case RED
case GREEN
case BLUE
}
enum Fruits:String, CaseIterable {
case MANGO, PINEAPPLE, ORANGE
}
enum Seasons:String, CaseIterable {
case WINTER, SPRING, AUTUMN, SUMMER
}
print(Colors.allCases)
print(Fruits.allCases)
print(Seasons.allCases)

Explanation

  • Lines 4, 10, and 14: We create some enums and make the case iterable using the CaseIterable method.
  • Lines 18–20: We print the cases of the enums that we created using the allCases method.

Free Resources