在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.Swift编程语言iBooks。 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 = "one"
case two = "two"
case three = "three"
}
let anEnum = StringEnum(rawValue: "one")!
print("anEnum = \"\(anEnum.rawValue)\"")
注意:在每种情况下,您不需要写=一等。默认字符串值与案例名称相同,因此调用 .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
如果您需要字符串值以包含作为案例值一部分无效的空格,则需要显式设置字符串。因此,
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 =one
anEnum = "one"
但是,如果你想要 case
/ code>显示value 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屋!