如何从字符串中创建枚举
在Swift 2中,您可以从字符串中创建枚举吗?
enum Food : Int { case Pizza, Pancakes }
let str = "Pizza"
let food = Food(name:str) // for example
最后一行不起作用,但我正在寻找类似的东西。像在Java中一样,您可以说food.valueof(“ pizza”)
。
编辑:我不能将字符串用作原始值。
In Swift 2, can you create an enum from a string?
enum Food : Int { case Pizza, Pancakes }
let str = "Pizza"
let food = Food(name:str) // for example
That last line doesn't work, but I'm looking for something like it. Like in Java, you can say Food.valueOf("Pizza")
.
Edit: I can't use a String as a raw value.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您可以为枚举创建一个初始化器,该枚举将
String
作为参数创建。从那里,您切换到字符串,将自我的价值设置为特定情况:这样:You can create an initializer for the enum that takes a
String
as a parameter. From there, you switch over the string to set the value of self to a specific case like so:没有周围的编译器来检查详细信息,而是类似的内容:
Don't have a compiler around to check the details but something like:
您可以设置原始值为字符串的枚举,然后通过指定原始值来创建枚举。这接近您的要求。
You can set up Enums where the raw value is a string, and then create an enum by specifying a raw value. That's close to what you are asking for.
伊恩(Ian)的答案很棒,但是根据您的需要,您可能更喜欢具有失败初始化器的枚举:
Ian's answer is great but, according to your needs, you may prefer an enum with a failable initializer: