Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift check type against a generic type

Tags:

swift

I've a generic function with 1 parameter and want to check the type of the passed parameter with the generic type. Something like this:

func generic<T>(parameter: AnyObject) -> Bool {     if parameter is T {         return true     } else {         return false     } } 

But I don't know how to call this

generic<String>("Hello") 

Gives me a compiler error: "Cannot explicitly specialize a generic function generic("Hello")

like image 601
mohamede1945 Avatar asked Jan 02 '15 18:01

mohamede1945


People also ask

Is it possible to inherit from a generic type?

An attribute cannot inherit from a generic class, nor can a generic class inherit from an attribute.

What is T type Swift?

The placeholder type T is used in the function declaration. It tells Swift that this function can find any item in any array, as long as the foundItem and items in the array are of the same type. This makes sense — you want to look for a T value in an array of T values.


2 Answers

You cannot tell a function what the types of its generic placeholders are (unlike with a generic struct). It must infer them from the context e.g. its arguments.

One way to do what you want is to add another argument related to type T. Rather than pass in a dummy value, you could use the metatype of the type you want:

func generic<T>(parameter: AnyObject, type: T.Type) -> Bool {     if parameter is T {         return true     } else {         return false     } }  let o: AnyObject = "hello" generic(o, String.self)    // true generic(o, NSString.self)  // also true generic(o, Int.self)       // false 

However, I would ask you, what is it you think you're achieving here? You've essentially done nothing more than implement is as a function:

o is String     // true o is NSString   // true o is Int        // false 

The point of generics is to operate on arguments generically, but you aren't giving the function any argument of a specific type to actually do any work on (hence the inability to infer one).

like image 68
Airspeed Velocity Avatar answered Sep 22 '22 20:09

Airspeed Velocity


Checking if generic type is which class.

protocol Some {} class SomeClass: Some {} class AClass: Some {} func test(_ t: T) -> String {     if T.self == SomeClass.self {         return "Some Class"     } else {         return "Another Class"     } }  print(test(SomeClass())) // Some Class print(test(AClass())) // Another Class 
like image 41
Brownsoo Han Avatar answered Sep 23 '22 20:09

Brownsoo Han