对于给定的通用函数
@H_502_6@
func myGenericFunction< T>() – > T {}@H_502_6@
我可以设置泛型将使用的类@H_502_6@
let _:Bool = myGenericFunction()@H_502_6@
有没有办法做到这一点所以我不必在另一条线上单独定义变量?@H_502_6@
例如:anotherFunction(myGenericFunction():Bool)@H_502_6@
解决方法
编译器需要一些上下文来推断类型T.
变量赋值,可以使用类型注释或强制转换来完成:
变量赋值,可以使用类型注释或强制转换来完成:
@H_502_6@
@H_502_6@
let foo: Bool = myGenericFunction() let bar = myGenericFunction() as Bool
如果anotherFunction接受Bool参数@H_502_6@
@H_502_6@
anotherFunction(myGenericFunction())
只是工作,然后从参数类型推断出T.@H_502_6@
如果anotherFunction采用泛型参数,那么
演员再次工作:@H_502_6@
@H_502_6@
anotherFunction(myGenericFunction() as Bool)
@H_502_6@
func myGenericFunction<T>(_ type: T.Type) -> T { ... } let foo = myGenericFunction(Bool.self) anotherFunction(myGenericFunction(Bool.self))
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。