'How can use Protocol in closure?

I got this closure in blew, now I want use Numeric protocol instead of Double, how I can do this?

let test: (Double) -> Double = { value in
    
    // some work ...
    
    return value
}

what I tried so far:

let test<T>: (T) -> T where T: Numeric = { value in
    
    // some work ...
    
    return value
}


Solution 1:[1]

I believe the problem here is that generics in Swift are invariant. E.g. Numeric<Double> and Numeric<Int> are completely unrelated types. Any reason why you can't convert this to a function instead?

import Foundation

func test<T: Numeric>(value: T) -> T {
    return value + 1
}

let a = test(value: 10)
print(a)

Alternatively, you can wrap the closure in a struct, like this answer, but at that point, just use a function: https://stackoverflow.com/a/25407534/1144632

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1