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]