在Swift中的枚举中传递并打印所有案例 [英] Pass and print all cases in an enum in Swift

查看:102
本文介绍了在Swift中的枚举中传递并打印所有案例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑以下简单的枚举:

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)

预期结果:

ABC
XYZ

注意:我可以迭代。但我不知道如何通过枚举。

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

推荐答案

您可以定义一个通用函数,该函数将类型作为参数,该类型为 CaseIterable RawRepresentable

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)
    }
}

用法:

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

printEnumCases(MyEnum.self)

这篇关于在Swift中的枚举中传递并打印所有案例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆