3
通用T回流对于给定的泛型函数的迅速
func myGenericFunction<T>() -> T { }
我可以设置集类型是什么类,通用将与
let _:Bool = myGenericFunction()
是有办法做到这样我不必在另一行分别定义一个变量?
例如:anotherFunction(myGenericFunction():Bool)
通用T回流对于给定的泛型函数的迅速
func myGenericFunction<T>() -> T { }
我可以设置集类型是什么类,通用将与
let _:Bool = myGenericFunction()
是有办法做到这样我不必在另一行分别定义一个变量?
例如:anotherFunction(myGenericFunction():Bool)
编译器需要一些背景来推断类型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))
感谢您的全面回答 – wyu
你不能“明确地专门化一个通用函数”。我只是在做这方面的一些研究。它是在邮件列表中提出的,但似乎没有任何地方:https://lists.swift.org/pipermail/swift-evolution/Week-of-Mon-20160523/018960.html –