Switching on a generic type?

后端 未结 1 1768
情深已故
情深已故 2020-12-10 23:52

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

Here\'s an example of what I mean:

func doSomething(type: T.Type) {
    switch type {
          


        
相关标签:
1条回答
  • 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.

    0 讨论(0)
提交回复
热议问题