简体   繁体   中英

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:

//-- 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 :

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. 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.

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. In that case an additional argument must be introduced into a method signature

func foo<T>(t: T)

let x = foo(Int.self)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM