Ken Zhang Ken Zhang - 1 year ago 107
Swift Question

is it possible to create a generic closure in Swift?

func myfunc<T>(i:T) -> T {
return i

is it possible to make this generic function a closure?

let myfunc = { <T>(i:T) -> T in
return i

this doesn't work...

Answer Source

No, because variables and expressions can't be generic. There are only generic functions and generic types.

To clarify: In some languages you can have types with a universal quantifier, like forall a. a -> a. But in Swift, types cannot have a universal quantifier. So expressions and values cannot be themselves generic. Function declarations and type declarations can be generic, but when you use such a generic function or an instance of such a generic type, some type (which could be a real type or a type variable) is chosen as the type argument, and thereafter the value you get is no longer itself generic.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download