[英]Swift - Cannot explicitly specialize a generic function
I am running into a compiler issue.我遇到了编译器问题。 It happens when I use SwiftTask, and Async, here is a sample:
当我使用 SwiftTask 和 Async 时会发生这种情况,这是一个示例:
//-- Generic Method //-- 通用方法
import Async
import SwiftTask
class AsyncTask {
func background<T>(job: (((Float -> Void), (T -> Void), (NSError -> Void), SwiftTask.TaskConfiguration) -> Void)) -> SwiftTask.Task<Float, T, NSError> {
return SwiftTask.Task<Float, T, NSError> { (progress: (Float -> Void), fulfill: (T -> Void), reject: (NSError -> Void), configure: SwiftTask.TaskConfiguration) -> Void in
Async.background {
job(progress, fulfill, reject, configure)
return
}
return
}
}
}
Now that compiles, but when I try to use the generic like so:现在可以编译了,但是当我尝试像这样使用泛型时:
//-- Using the Generic Method //-- 使用泛型方法
let task = AsyncTask.background<MyAwesomeObject> { progress, fulfill, reject, configure in
let obj = MyAwesomeObject()
//-- ... do work here
fulfill(obj)
return
}
I then get the following error Cannot explicitly specialize a generic function然后我收到以下错误无法明确专门化通用函数
Give the closure an explicit type to fix T
:给闭包一个明确的类型来修复
T
:
let task = AsyncTask.background{ (progress: Float -> Void, fulfill: MyAwesomeObject -> Void, reject: NSError -> Void, configure: SwiftTask.TaskConfiguration) -> Void in
let obj = MyAwesomeObject()
//-- ... do work here
fulfill(obj)
}
The way you try to specialise a generic function is called explicit specialization
.It's not a syntax error, it's a semantic error.您尝试特化泛型函数的方式称为
explicit specialization
这不是语法错误,而是语义错误。 At parse time, there's no difference between在解析时,两者之间没有区别
let x = foo<Int>()
and和
let arr = Array<Int>()
But in the current version of Swift language which is 5.1 this is not permitted but in future versions it could be permited to use it.但是在当前版本的 Swift 语言 5.1 中这是不允许的,但在未来的版本中可以允许使用它。
Today, a type arguments of a generic function are always determined via type inference.今天,泛型函数的类型参数总是通过类型推断来确定的。 For example, given:
例如,给定:
func foo<T>()
let x = foo() as Int
// or
let x: Int = foo()
or T is determined via the argument's type.或 T 由参数的类型确定。 In that case an additional argument must be introduced into a method signature
在这种情况下,必须在方法签名中引入一个额外的参数
func foo<T>(t: T)
let x = foo(Int.self)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.