How to get enum from raw value in Swift?

前端 未结 7 1098
一向
一向 2020-12-13 23:25

I\'m trying to get enum type from raw value:

enum TestEnum: String {
    case Name
    case Gender
    case Birth

    var rawValue: String {
        switch          


        
7条回答
  •  执念已碎
    2020-12-14 00:12

    Full working example:

    enum TestEnum: String {
        case name = "A Name"
        case otherName
        case test = "Test"
    }
    
    let first: TestEnum? = TestEnum(rawValue: "A Name")
    let second: TestEnum? = TestEnum(rawValue: "OtherName")
    let third: TestEnum? = TestEnum(rawValue: "Test")
    
    print("\(first), \(second), \(third)")
    

    All of those will work, but when initializing using a raw value it will be an optional. If this is a problem you could create an initializer or constructor for the enum to try and handle this, adding a none case and returning it if the enum couldn't be created. Something like this:

    static func create(rawValue:String) -> TestEnum {
            if let testVal = TestEnum(rawValue: rawValue) {
                return testVal
            }
            else{
                return .none
            }
        }
    

提交回复
热议问题