In Swift, a generic function that returns a function of the same type gives me "Cannot explicitly specialize a generic function"

Viewed 375

This function takes a Void -> T function and returns a Void -> T function.

func future<T>(f: Void -> T) -> Void -> T {
    let queue = dispatch_queue_create("com.test.lockQueue", nil)
    var results: T?

    dispatch_async(queue) {
        results = f()
    }

    return {
        dispatch_sync(queue) {}
        return results!
    }
}

If I use it like this:

let f = future<Int> {
    NSThread.sleepForTimeInterval(2)
    return 10
}

I get the error "Cannot explicitly specialize a generic function".

If I however set the explicit type to Void -> Int like so:

let f: Void -> Int = future {
    NSThread.sleepForTimeInterval(2)
    return 10
}

It works but it doesn't look that good. Can I change the function so that the I can use it in the first example?

3 Answers
Related