Pass and print all cases in an enum in Swift

天大地大妈咪最大 提交于 2019-12-11 01:13:53

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!