简体   繁体   中英

get enum raw values from [Any] without downcasting

Say I have 5 different enums of String type, enum1:String, enum2:String ...

I have an array [Any] whose type is one of the 5 enums, is there a way to get the raw values of the array of enums without downcasting it to the specific enum type?

Instead of wrapping the different enums in an array of Any, you can create an new enum type which holds the other enum values. So you are always type safe and have access to raw value.

enum Enum1: String {
    case foo1 = "foo"
    case foo2 = "foo2"
}

enum Enum2: String {
    case bla1 = "bla"
    case bla2 = "bla2"
}


enum EnumType {
    case enum1(Enum1)
    case enum2(Enum2)
    case enum3(Enum2)
}

let array: [EnumType] = [
    EnumType.enum1(.foo1),
    EnumType.enum1(.foo2),
    EnumType.enum2(.bla1)]

for item in array {
    switch item {
    case .enum1(let value):
        print(value)
    case .enum2(let value):
        print(value)
    case .enum3(let value):
        print(value)
    }
}

Yes, you can do this:

Enum(rawValue:INDEX)

So for instance, if you have a Currency Enum:

public enum Currency : Int {

case EUR
case GBP
case SK
case NOK
case USD

public static let values : [Currency] = [EUR, GBP, SK, NOK, USD]

}

You can get the value like this:

Currency(rawValue: 0)

It will return EUR.

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