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

后端 未结 8 953
[愿得一人]
[愿得一人] 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 06:00

    In case with an enum with Int type you can do it so:

    enum MenuItem: Int {
        case One = 0, Two, Three, Four, Five //... as much as needs
    
        static func enumFromString(string:String) -> MenuItem? {
            var i = 0
            while let item = MenuItem(rawValue: i) {
                if String(item) == string { return item }
                i += 1
            }
            return nil
        }
    }
    

    And use:

    let string = "Two"
    if let item = MenuItem.enumFromString(string) {
        //in this case item = 1 
        //your code
    } 
    
    0 讨论(0)
  • 2020-12-14 06:04

    Riffing on djruss70's answer to create highly generalized solution:

    extension CaseIterable {
        static func from(string: String) -> Self? {
            return Self.allCases.first { string == "\($0)" }
        }
        func toString() -> String { "\(self)" }
    }
    

    Usage:

    enum Chassis: CaseIterable {
        case pieridae, oovidae
    }
    
    let chassis: Chassis = Chassis.from(string: "oovidae")!
    let string: String = chassis.toString()
    

    Note: this will unfortunately not work if the enum is declared @objc. As far as I know as of Swift 5.3 there is no way to get this to work with @objc enum's except brute force solutions (a switch statement).

    If someone happens to know of a way to make this work for @objc enums, I'd be very interested in the answer.

    0 讨论(0)
提交回复
热议问题