gpt4 book ai didi

swift - 在 Swift 中,是否可以将字符串转换为枚举?

转载 作者:IT王子 更新时间:2023-10-29 04:57:22 32 4
gpt4 key购买 nike

如果我有一个包含 a、b、c、d 情况的枚举,我可以将字符串“a”转换为枚举吗?

最佳答案

当然。枚举可以有一个原始值。引用文档:

Raw values can be strings, characters, or any of the integer orfloating-point number types

— Excerpt From: Apple Inc. “The Swift Programming Language.” iBooks. https://itun.es/us/jEUH0.l,

所以你可以使用这样的代码:

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)\"")

注意:你不需要在每个 case 后面写 = "one"等。默认字符串值与案例名称相同,因此调用 .rawValue 将只返回一个字符串

编辑

如果您需要字符串值包含诸如空格之类的内容,而这些内容作为大小写值的一部分是无效的,那么您需要显式设置字符串。所以,

enum StringEnum: String 
{
case one
case two
case three
}

let anEnum = StringEnum.one
print("anEnum = \"\(anEnum)\"")

给予

anEnum = "one"

但是,如果您希望 case one 显示“value one”,则需要提供字符串值:

enum StringEnum: String 
{
case one = "value one"
case two = "value two"
case three = "value three"
}

关于swift - 在 Swift 中,是否可以将字符串转换为枚举?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30009788/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com