Cannot explicitly specialize a generic function

后端 未结 7 2179
时光取名叫无心
时光取名叫无心 2020-12-04 11:06

I have issue with following code:

func generic1(name : String){
}

func generic2(name : String){
     generic1(name)
}


        
相关标签:
7条回答
  • 2020-12-04 11:44

    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.

    0 讨论(0)
自定义标题
段落格式
字体
字号
代码语言
提交回复
热议问题