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?
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 eitherE
orE?
. (You're wrappinginit?(rawValue:)
, which returns an optional becauserawValue
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 theRawValue
typealias that theRawRepresentable
protocol (which you've already given as a generic constraint) defines.So, here's your function:
Note that if you try something like this:
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: