如果我有一个枚举与案例a,b,c,d我可以把字符串“a”作为枚举?
当然。枚举可以有一个原始值。引用文档:
原文链接:https://www.f2er.com/swift/321193.htmlRaw values can be strings,characters,or any of the integer or
floating-point number types— Excerpt From: Apple Inc. “The Swift Programming Language.” iBooks. 07000,
所以你可以使用这样的代码:
enum StringEnum: String { case one = "one" case two = "two" case three = "three" } let anEnum = StringEnum(rawValue: "one")! print("anEnum = \"\(anEnum.rawValue)\"")
注意:在每种情况后,您不需要写=“一”等。默认字符串值与案例名称相同,因此调用.rawValue只返回一个字符串
编辑
如果需要字符串值包含诸如作为大小写值的一部分无效的空格,则需要显式设置字符串。所以,
enum StringEnum: String { case one case two case three } let anEnum = StringEnum.one print("anEnum = \"\(anEnum)\"")
给出
anEnum = “one”
但是如果你想要第一个显示“值一”,你将需要提供字符串值:
enum StringEnum: String { case one = "value one" case two = "value two" case three = "value three" }