Is it possible to declare a quick generalization for enumerations of a certain type?

Is it possible to have a function that allows any enumeration where rawValue has a specific type? For example, any enumeration that has a rawValue string.

+4
source share
2 answers

This can be done using generics and the keyword "where"

enum EnumString: String {
    case A = "test"
}

func printEnum<T: RawRepresentable where T.RawValue == String>(arg: T) {
    print(arg.rawValue)
}
printEnum(EnumString.A) //Prints "test"
+4
source

You can declare a generic type corresponding to a type RawRepresentablethat is a protocol that matches all enumerations declaring a primitive rawValue.

enum EnumA: Int {
    case A = 0
}

enum EnumB {
    case A
}

func doGenericSomething<T: RawRepresentable>(arg: T) {
    println(arg.rawValue)
}

doGenericSomething(EnumA.A) //OK
doGenericSomething(EnumB.A) //Error! Does not conform to protocol RawRepresentable

You cannot, however, specify the type of renaming rawValue in a generic format. For information, you can see the message here .

+1

All Articles