Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cannot explicitly specialize a generic function

Tags:

generics

swift

I have issue with following code:

func generic1<T>(name : String){ }  func generic2<T>(name : String){      generic1<T>(name) } 

the generic1(name) result to compiler error "Cannot explicitly specialize a generic function"

Is any way to avoid this error? I can't change signature of generic1 function, therefore it should be (String) -> Void

like image 935
Greyisf Avatar asked Jan 15 '15 14:01

Greyisf


People also ask

How do I call a generic function in Swift?

Solution. A generic function that you might need to use explicit specialization is the one that infer its type from return type—the workaround for this by adding a parameter of type T as a way to inject type explicitly. In other words, we make it infer from method's parameters instead.

Which is known as a generic function?

A generic function is a function that is declared with type parameters. When called, actual types are used instead of the type parameters.

What is generic function give example?

You can also define generic functions that take variable numbers of arguments in just the same way as ordinary functions. For example: (defgeneric foo (a . b)) defines a generic function (with no methods) taking at least one argument, with the second always being of class <list>.


1 Answers

I also had this problem and I found a workaround for my case.

In this article the author has the same problem

https://www.iphonelife.com/blog/31369/swift-programming-101-generics-practical-guide

So the problem seems to be, that the compiler needs to infer the type of T somehow. But it isn't allowed to simply use generic< type >(params...).

Normally, the compiler can look for the type of T, by scanning the parameter types because this is where T is used in many cases.

In my case it was a little bit different, because the return type of my function was T. In your case it seems that you haven't used T at all in your function. I guess you just simplified the example code.

So I have the following function

func getProperty<T>( propertyID : String ) -> T 

And in case of, for instance

getProperty<Int>("countProperty") 

the compiler gives me the error:

Cannot explicitly specialize a generic function

So, to give the compiler another source of information to infer the type of T from, you have to explicitly declare the type of the variable the return value is saved in.

var value : Int = getProperty("countProperty") 

This way the compiler knows that T has to be an integer.

So I think overall it simply means that if you specify a generic function you have to at least use T in your parameter types or as a return type.

like image 173
ThottChief Avatar answered Nov 16 '22 01:11

ThottChief