swiftgenerics

Switching on a generic type?


Is it possible to switch on a generic type in Swift?

Here's an example of what I mean:

func doSomething<T>(type: T.Type) {
    switch type {
    case String.Type:
        // Do something
        break;
    case Int.Type:
        // Do something
        break;
    default:
        // Do something
        break;
    }
}

When trying to use the code above, I get the following errors:

Binary operator '~=' cannot be applied to operands of type 'String.Type.Type' and 'T.Type'
Binary operator '~=' cannot be applied to operands of type 'Int.Type.Type' and 'T.Type'

Is there a way to switch on a type, or to achieve something similar? (calling a method with a generic and performing different actions depending on the type of the generic)


Solution

  • You need the is pattern:

    func doSomething<T>(type: T.Type) {
        switch type {
        case is String.Type:
            print("It's a String")
        case is Int.Type:
            print("It's an Int")
        default:
            print("Wot?")
        }
    }
    

    Note that the break statements are usually not needed, there is no "default fallthrough" in Swift cases.