在 Swift 中,是否可以将字符串转换为枚举? [英] In Swift, is it possible to convert a string to an enum?
问题描述
如果我有一个包含 a,b,c,d 的枚举,是否可以将字符串a"转换为枚举?
If I have an enum with the cases a,b,c,d is it possible for me to cast the string "a" as the enum?
推荐答案
好的.枚举可以具有原始值.引用文档:
Sure. Enums can have a raw value. To quote the docs:
原始值可以是字符串、字符或任何整数或浮点数类型
Raw values can be strings, characters, or any of the integer or floating-point number types
——摘自:Apple Inc.The Swift Programming Language".电子书.https://itun.es/us/jEUH0.l,
— Excerpt From: Apple Inc. "The Swift Programming Language." iBooks. https://itun.es/us/jEUH0.l,
所以你可以使用这样的代码:
So you can use code like this:
enum StringEnum: String
{
case one = "value one"
case two = "value two"
case three = "value three"
}
let anEnum = StringEnum(rawValue: "value one")!
print("anEnum = "(anEnum.rawValue)"")
注意:你不需要写 = one";等等.在每个案例之后.默认字符串值与案例名称相同,因此调用 .rawValue
只会返回一个字符串
Note: You don't need to write = "one" etc. after each case. The default string values are the same as the case names so calling .rawValue
will just return a string
如果您需要字符串值包含不能作为 case 值一部分的空格之类的东西,那么您需要显式设置字符串.所以,
If you need the string value to contain things like spaces that are not valid as part of a case value then you need to explicitly set the string. So,
enum StringEnum: String
{
case one
case two
case three
}
let anEnum = StringEnum.one
print("anEnum = "(anEnum)"")
给予
anEnum = 一个"
anEnum = "one"
但是如果你想让 case
one
显示值一"您需要提供字符串值:
But if you want case
one
to display "value one" you will need to provide the string values:
enum StringEnum: String
{
case one = "value one"
case two = "value two"
case three = "value three"
}
这篇关于在 Swift 中,是否可以将字符串转换为枚举?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!