Robert Vaessen Robert Vaessen - 1 year ago 88
Swift Question

Is it possible to assign a generic function to a variable?

func function1(arg: Int) -> Int { return arg }

func function2<T>(arg: T) -> T { return arg }

let f1 = function1 // No problem

let f2 = function2<Int> // Cannot explicitly specialize a generic function

A current short coming of the language?

Answer Source

You can let Swift infer the specialization of function2 by the explicit type annotation of f2:

let f2: (Int) -> Int = function2

Alternatively, use an intermediate specializer function which supplies the explicit type annotation

func specialize1Dmap<T>(_ f: @escaping (T) -> T, as _: T.Type) -> (T) -> T { return f }
let f2int = specialize1Dmap(function2, as: Int.self)
let f2str = specialize1Dmap(function2, as: String.self)
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download