Reputation: 1146
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?
Upvotes: 9
Views: 10223
Reputation:
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]
Upvotes: 3
Reputation: 130102
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.
Upvotes: 17