Is it possible to generate enum from <String> array in Swift?
Here's my listing:
enum myEnum : Int {
case apple = 0
case orange
case lemon
}
I would like to create it from an array. Array elements can be the name of enumerations.
let myEnumDictionary : Array<String> = ["apple","orange","lemon"]
So, is it possible to create enums from an array?
No, It is Immpossible. Similarly, you cannot create classes from arrays.
The enumerations must be compiled. You cannot create them dynamically.
If your enum rawValue
needs to be Int, you can either map from an array of integer raw values ββto a collection of enumerations, or add a convenience initializer that returns an enumeration that matches the 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 type rawValue
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 to simply provide a list of lists of enums:
let myEnumDictionary: [MyEnum] = [.apple, .orange, .lemon]