Swift:将枚举值转换为字符串? [英] Swift: Convert enum value to String?

查看:52
本文介绍了Swift:将枚举值转换为字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给定以下枚举:

enum Audience {案例公开案例朋友私人案例}

如何从下面的 audience 常量中获取字符串 "Public"?

让观众 = Audience.Public

解决方案

不确定在哪个 Swift 版本中添加了此功能,但现在(Swift 2.1)您只需要以下代码:

enum Audience : String {案件公开案例朋友私人案例}让观众 = Audience.public.rawValue//公开"

<块引用>

当字符串用于原始值时,每种情况的隐含值是案例名称的文本.

[...]

enum CompassPoint : String {案例北,南,东,西}

在上面的例子中,CompassPoint.south 有一个隐含的原始值南",等等.

你用它的 rawValue 访问一个枚举 case 的原始值属性:

让sunsetDirection = CompassPoint.west.rawValue//日落方向是西"

来源.>

Given the following enum:

enum Audience {
    case Public
    case Friends
    case Private
}

How do I get the string "Public" from the audience constant below?

let audience = Audience.Public

解决方案

Not sure in which Swift version this feature was added, but right now (Swift 2.1) you only need this code:

enum Audience : String {
    case public
    case friends
    case private
}

let audience = Audience.public.rawValue // "public"

When strings are used for raw values, the implicit value for each case is the text of that case’s name.

[...]

enum CompassPoint : String {
    case north, south, east, west
}

In the example above, CompassPoint.south has an implicit raw value of "south", and so on.

You access the raw value of an enumeration case with its rawValue property:

let sunsetDirection = CompassPoint.west.rawValue
// sunsetDirection is "west"

Source.

这篇关于Swift:将枚举值转换为字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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