wyu wyu - 1 month ago 12
Swift Question

Set type of generic T return in swift

For a given generic function

func myGenericFunction<T>() -> T { }


I can set what class that generic will be with

let _:Bool = myGenericFunction()


is there a way to do this so I don't have to define a variable separately on another line?

ex:
anotherFunction(myGenericFunction():Bool)

Answer

The compiler needs some context to infer the type T. In a variable assignment, this can be done with a type annotation or a cast:

let foo: Bool = myGenericFunction()
let bar = myGenericFunction() as Bool

If anotherFunction takes a Bool parameter then

anotherFunction(myGenericFunction())

just works, T is then inferred from the parameter type.

If anotherFunction takes a generic parameter then the cast works again:

anotherFunction(myGenericFunction() as Bool)

A different approach would be to pass the type as an argument instead:

func myGenericFunction<T>(_ type: T.Type) -> T { ... }

let foo = myGenericFunction(Bool.self)
anotherFunction(myGenericFunction(Bool.self))
Comments