在swift中设置通用T返回的类型

wyu*_*wyu 5 swift swift3

对于给定的通用函数

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

我可以设置泛型将使用的类

let _:Bool = myGenericFunction()

有没有办法做到这一点所以我不必在另一条线上单独定义变量?

例如: anotherFunction(myGenericFunction():Bool)

Mar*_*n R 6

编译器需要一些上下文来推断类型T.在变量赋值中,可以使用类型注释或强制转换来完成:

let foo: Bool = myGenericFunction()
let bar = myGenericFunction() as Bool
Run Code Online (Sandbox Code Playgroud)

如果anotherFunction接受一个Bool参数

anotherFunction(myGenericFunction())
Run Code Online (Sandbox Code Playgroud)

只是工作,T然后从参数类型推断.

如果anotherFunction采用通用参数,则转换再次起作用:

anotherFunction(myGenericFunction() as Bool)
Run Code Online (Sandbox Code Playgroud)

另一种方法是将类型作为参数传递:

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

let foo = myGenericFunction(Bool.self)
anotherFunction(myGenericFunction(Bool.self))
Run Code Online (Sandbox Code Playgroud)