4

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?

2
  • 1
    Your function has a return type of Void, for one thing. Commented Jan 27, 2015 at 17:38
  • Sorry my bad, but that was just a typo Commented Jan 27, 2015 at 22:37

1 Answer 1

9

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))
Sign up to request clarification or add additional context in comments.

1 Comment

Footnote: presumably your "real" intended use of this function puts some useful logic inside — otherwise there's not much point to just putting a generic wrapper around init(rawValue:), because you still need to know (or be able to infer) the enum type at the call site.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.