Search code examples
swiftgenericsenumsrawrepresentable

How can I create an instance of a generic enum in Swift


I'm trying to write a function in swift that creates a rawValue enum in a generic function like this:

enum STATE: String {
    case OK = "OK"
    case ERROR = "ERROR"
}

func createEnum<E: RawRepresentable>(rawValue: T.Type) {
    return E(rawValue: rawValue) // compiler error 
}

Am I missing anything?


Solution

  • As noted, your function needs a return type if you want it to return anything. Since you seem to want to use the function to create a value of the specified enum type, that return type should probably be either E or E?. (You're wrapping init?(rawValue:), which returns an optional because rawValue may not map to one of the enum cases. So you either want to pass the optional through to your caller or have some logic in your function to unwrap it and handle the nil case.)

    Your parameter rawValue also needs a real type — T.Type is not a fully qualified type in your declaration. You can get at the raw value type of the enum using the RawValue typealias that the RawRepresentable protocol (which you've already given as a generic constraint) defines.

    So, here's your function:

    func createEnum<E: RawRepresentable>(rawValue: E.RawValue) -> E? {
         return E(rawValue: rawValue) 
    } 
    

    Note that if you try something like this:

    enum Foo: Int {
        case One = 1
        case Two = 2
    }
    createEnum(1)
    createEnum<Foo>(1)
    

    It won't work — the first one doesn't specify which specialization of the generic function to use, and the second doesn't work because Swift doesn't allow manual specialization of generic functions. Instead, you have to set it up so that type inference does its thing:

    let f: Foo? = createEnum(1)
    someFuncThatTakesAFoo(createEnum(1))