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

后端 未结 8 955
[愿得一人]
[愿得一人] 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
    } 
    

提交回复
热议问题