Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

swift

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?

like image 958
Verticon Avatar asked Nov 19 '16 14:11

Verticon


People also ask

How do you declare a generic variable in Java?

A Generic Version of the Box Class To update the Box class to use generics, you create a generic type declaration by changing the code "public class Box" to "public class Box<T>". This introduces the type variable, T, that can be used anywhere inside the class.

What is a generic in typescript?

Generics allow creating 'type variables' which can be used to create classes, functions & type aliases that don't need to explicitly define the types that they use. Generics makes it easier to write reusable code.


1 Answers

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)
like image 97
dfrib Avatar answered Oct 20 '22 22:10

dfrib