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,684
  • 6
  • 40
  • 67

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
  • 510,973
  • 84
  • 1,183
  • 1,314
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
  • 3,903
  • 4
  • 20
  • 36