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")
An attribute cannot inherit from a generic class, nor can a generic class inherit from an attribute.
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.
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).
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
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