Robert Vaessen Robert Vaessen - 7 months ago 57
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?


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)