In Swift, is it possible to convert a string to an enum?

后端 未结 8 970
[愿得一人]
[愿得一人] 2020-12-14 05:17

If I have an enum with the cases a,b,c,d is it possible for me to cast the string \"a\" as the enum?

8条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-12-14 05:55

    In Swift 4.2, the CaseIterable protocol can be used for an enum with rawValues, but the string should match against the enum case labels:

    enum MyCode : String, CaseIterable {
    
        case one   = "uno"
        case two   = "dos"
        case three = "tres"
    
        static func withLabel(_ label: String) -> MyCode? {
            return self.allCases.first{ "\($0)" == label }
        }
    }
    

    usage:

    print(MyCode.withLabel("one")) // Optional(MyCode.one)
    print(MyCode(rawValue: "uno"))  // Optional(MyCode.one)
    

提交回复
热议问题