在Swift中,是否可以将字符串转换为枚举?
发布时间:2020-12-14 06:07:10 所属栏目:百科 来源:网络整理
导读:如果我有一个枚举与案例a,b,c,d我可以把字符串“a”作为枚举? 当然。枚举可以有一个原始值。引用文档: Raw values can be strings,characters,or any of the integer or floating-point number types — Excerpt From: Apple Inc. “The Swift Programm
如果我有一个枚举与案例a,b,c,d我可以把字符串“a”作为枚举?
当然。枚举可以有一个原始值。引用文档:
所以你可以使用这样的代码: 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)"") 给出
但是如果你想要第一个显示“值一”,你将需要提供字符串值: enum StringEnum: String { case one = "value one" case two = "value two" case three = "value three" } (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |