joehinkle11
joehinkle11

Reputation: 512

Reference to generic function in Swift

In Swift, you can create a reference to a function in the form of a closure. For example:

func simpleFunc(param: Int) {
    
}
let simpleFuncReference = simpleFunc(param:) // works just fine

But in one case, I have a function with a generic parameter like this:

func hardFunc<T: StringProtocol>(param: T) {
    
}
let hardFuncReference = hardFunc(param:) // "Generic parameter 'T' could not be inferred"

To try to remove that error, I attempted to explicitly specify the type, but immediately another error comes up.

func hardFunc<T: StringProtocol>(param: T) {
    
}
let hardFuncReference = hardFunc(param:) // "Cannot explicitly specialize a generic function"

Is there a way I can get a reference to hardFunc as a closure?

Upvotes: 0

Views: 185

Answers (1)

Chip Jarred
Chip Jarred

Reputation: 2785

As you already guessed, you have to help type inference out a little:

func hardFunc<T: StringProtocol>(param: T) {
    
}
let hardFuncReference:(String) -> Void  = hardFunc(param:) 

Note that you do have to specify the particular type that you're specializing on, but in this case you do it by specifying the type of the variable you're assigning the closure to.

You can't keep it generic unless you're in a generic context specifying that it's generic on the same type. So this will work too

struct Foo<T: StringProtocol> {
    let hardFuncReference:(T) -> Void  = hardFunc(param:)
}

Upvotes: 1

Related Questions