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 casesprint(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 enumerationsenum Colors:Int, CaseIterable {case REDcase GREENcase 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
CaseIterablemethod. - Lines 18–20: We print the cases of the enums that we created using the
allCasesmethod.