Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
975 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 Reply

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...