Swift:将枚举值转换为String? [英] Swift: Convert enum value to String?
本文介绍了Swift:将枚举值转换为String?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
鉴于以下枚举:
enum Audience {
case Public
case Friends
case Private
}
如何获取字符串公开
从受众群体
常数以下?
How do I get the string "Public"
from the audience
constant below?
let audience = Audience.Public
推荐答案
添加了这个功能的Swift版本,但现在( Swift 2.1 )只需要以下代码:
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"
当字符串用于原始值时,每个案例
是该案例名称的文本。
[...]
enum CompassPoint: String {
case North, South, East, West
}
在上面的例子中,CompassPoint.South有一个隐含的原始
South的值,等等。
In the example above, CompassPoint.South has an implicit raw value of "South", and so on.
您可以使用其rawValue
属性访问枚举大小写的原始值:
You access the raw value of an enumeration case with its rawValue property:
let sunsetDirection = CompassPoint.West.rawValue
// sunsetDirection is "West"
这篇关于Swift:将枚举值转换为String?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文