加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-14 04:42:45 所属栏目:百科 来源:网络整理
导读:对于给定的通用函数 func myGenericFunction T() – T {} 我可以设置泛型将使用的类 let _:Bool = myGenericFunction() 有没有办法做到这一点所以我不必在另一条线上单独定义变量? 例如:anotherFunction(myGenericFunction():Bool) 解决方法 编译器需要
对于给定的通用函数

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))

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读