2016-10-10 60 views
3

通用T回流对于给定的泛型函数的迅速

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

我可以设置集类型是什么类,通用将与

let _:Bool = myGenericFunction()

是有办法做到这样我不必在另一行分别定义一个变量?

例如:anotherFunction(myGenericFunction():Bool)

+1

你不能“明确地专门化一个通用函数”。我只是在做这方面的一些研究。它是在邮件列表中提出的,但似乎没有任何地方:https://lists.swift.org/pipermail/swift-evolution/Week-of-Mon-20160523/018960.html –

回答

5

编译器需要一些背景来推断类型T。在 变量赋值,这可以用一个类型注释或铸造完成:

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

如果anotherFunction需要Bool参数然后

anotherFunction(myGenericFunction()) 

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

如果anotherFunction需要通用参数则 投再次工作:

anotherFunction(myGenericFunction() as Bool) 

一种不同的方法将是通过类型作为参数 代替:

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

let foo = myGenericFunction(Bool.self) 
anotherFunction(myGenericFunction(Bool.self)) 
+0

感谢您的全面回答 – wyu