一尘不染

如何从Swift的原始值中获取枚举?

swift

我试图从原始值获取枚举类型:

enum TestEnum: String {
    case Name
    case Gender
    case Birth

    var rawValue: String {
        switch self {
        case .Name: return "Name"
        case .Gender: return "Gender"
        case .Birth: return "Birth Day"
        }
    }
}

let name = TestEnum(rawValue: "Name")       //Name
let gender = TestEnum(rawValue: "Gender")   //Gender

但是似乎rawValue对于带空格的字符串不起作用:

let birth = TestEnum(rawValue: "Birth Day") //nil

任何建议如何获得它?


阅读 328

收藏
2020-07-07

共1个答案

一尘不染

太复杂了,只需将原始值直接分配给案例

enum TestEnum: String {
  case Name = "Name"
  case Gender = "Gender"
  case Birth = "Birth Day"
}

let name = TestEnum(rawValue: "Name")!       //Name
let gender = TestEnum(rawValue: "Gender")!   //Gender
let birth = TestEnum(rawValue: "Birth Day")! //Birth

如果案例名称与原始值匹配,您甚至可以忽略它

enum TestEnum: String {
  case Name, Gender, Birth = "Birth Day"
}

在Swift 3+中,所有枚举都是 lowercased

2020-07-07