wyu wyu - 1 year ago 87
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?


Answer Source

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


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)
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download