2

Consider this simple enum:

enum myEnum: String {
    case abc = "ABC"
    case xyz = "XYZ"
}

I want to write a function that can print all cases in an enum. Like..

printEnumCases(myEnum)

Expected result:

ABC
XYZ

Note: I can able to iterate an enum like this. But I don't know how to pass the enum.

Confused
  • 3,846
  • 7
  • 45
  • 72

2 Answers2

4

You can define a generic function which takes a type as argument which is CaseIterable and RawRepresentable:

func printEnumCases<T>(_: T.Type) where T: CaseIterable & RawRepresentable {
    for c in T.allCases {
        print(c.rawValue)
    }
}

Usage:

enum MyEnum: String, CaseIterable {
    case abc = "ABC"
    case xyz = "XYZ"
}

printEnumCases(MyEnum.self)
Martin R
  • 529,903
  • 94
  • 1,240
  • 1,382
0

Make your enum conform to CaseIterable and then you'll be able to use .allCases.

enum myEnum: String, CaseIterable {
    case abc = "ABC"
    case xyz = "XYZ"
}

myEnum.allCases.forEach { x -> print(x.rawValue) }

CaseIterable docs

Kon
  • 4,023
  • 4
  • 24
  • 38