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)
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.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With