Pass and print all cases in an enum in Swift

Viewed 532

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.

2 Answers

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)

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

Related