Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Switching on a generic type?

Tags:

generics

swift

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)

like image 939
Jack Wilsdon Avatar asked Oct 18 '15 21:10

Jack Wilsdon


People also ask

How do you know if a type is generic?

To examine a generic type and its type parametersGet an instance of Type that represents the generic type. In the following code, the type is obtained using the C# typeof operator ( GetType in Visual Basic, typeid in Visual C++). See the Type class topic for other ways to get a Type object.

What is generic data type in Java?

Generics means parameterized types. The idea is to allow type (Integer, String, … etc., and user-defined types) to be a parameter to methods, classes, and interfaces. Using Generics, it is possible to create classes that work with different data types.

How do you declare a generic type in Java?

A Generic Version of the Box Class To update the Box class to use generics, you create a generic type declaration by changing the code "public class Box" to "public class Box<T>". This introduces the type variable, T, that can be used anywhere inside the class.

What is meant by generic type?

Definition: “A generic type is a generic class or interface that is parameterized over types.” Essentially, generic types allow you to write a general, generic class (or method) that works with different types, allowing for code re-use.


1 Answers

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.

like image 71
Martin R Avatar answered Sep 19 '22 04:09

Martin R