问题
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.
回答1:
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)
回答2:
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
来源:https://stackoverflow.com/questions/56857933/pass-and-print-all-cases-in-an-enum-in-swift