简体   繁体   中英

Is it possible to generate enum from Array<String> in Swift?

Here is my enum:

enum myEnum : Int {
    case apple = 0
    case orange
    case lemon
}

I would like to create it from an array. The array elements could be the name of the enums.

let myEnumDictionary : Array<String> = ["apple","orange","lemon"]

So is it possible to create enums from an array?

No, it's not possible. In the same way you can't create classes from arrays.

Enums must be compiled. You can't create them dynamically.

If your enum rawValue must be an Int, you could either map from an array of integer raw values to a collection of enums, or add a convenience initializer which returns the enum matching a given string literal:

enum MyEnum : Int {
    case apple = 0
    case orange
    case lemon

    init?(fruit: String) {
        switch fruit {
        case "apple":
            self = .apple
        case "orange":
            self = .orange
        case "lemon":
            self = .lemon
        default:
            return nil
        }
    }
}

let myEnumDictionary = [0, 1, 2].map{ MyEnum(rawValue: $0) }.flatMap{ $0 }

let myEnumDictionary2 = ["apple", "orange", "lemon"].map{ MyEnum(fruit: $0) }.flatMap{ $0 }

If the enum rawValue type was a string, you wouldn't need to provide an initializer:

enum MyEnum: String {
    case apple
    case orange
    case lemon
}

let myEnumDictionary = ["apple", "orange", "lemon"].map{ MyEnum(rawValue: $0) }.flatMap{ $0 }

Of course, the easiest way to create an array of enums is just to provide a literal list of enums:

let myEnumDictionary: [MyEnum] = [.apple, .orange, .lemon]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM