Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

swift - 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)

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...