不能明确地专门化一个通用函数 [英] Cannot explicitly specialize a generic function
问题描述
func generic1< T>(name:String){
}
func generic2< T>(name:String){
generic1< T>(name)
}
$ b generic1(name)导致编译器错误Can not explicit specialize a generic function
有什么办法可以避免这个错误?我无法更改generic1函数的签名,因此它应该是(String) - > Void
我也有这个问题我找到了解决方案。
在这篇文章中,作者有同样的问题
https://www.iphonelife.com/blog/31369/swift-programming-101-generics-practical-指南
所以问题似乎是,编译器需要以某种方式推断T的类型。但是,不允许简单地使用通用<键入>(params ...)。通常情况下,编译器可以通过扫描参数类型来查找T的类型,因为这在很多情况下都是使用T的地方。
在我的情况中,它有点不同,因为我函数的返回类型是T.在你的情况中,你似乎还没有使用过T你的功能。我猜你只是简化了示例代码。
所以我有以下函数:
pre code> func getProperty< T>(propertyID:String) - > T
例如
getProperty< int>(countProperty)
编译器给了我
$ pre $ $ code不能明确地专门化一个通用函数
code $
因此,为了给编译器提供另一个信息来源来推断T from的类型,必须显式声明返回值保存的变量类型。
var value:Int = getProperty(countProperty)
这样编译器知道T必须是一个整数。
所以我认为总的来说,它仅仅意味着如果你指定了一个泛型函数,你至少必须在你的参数类型中使用T或者作为返回类型。
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
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
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.
这篇关于不能明确地专门化一个通用函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!