在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)) (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
相关内容
- strut2.xml配置文件4_中
- PostgreSQL:Java使用CopyManager实现客户端文件COPY导入 .
- c# – 估计GUID内的数字发生概率
- ruby-on-rails – 错误乘客没有看到环境变量?
- swift – 如何从UnsafeMutableRawPointer中获取字节?
- visual-c – 如何在WTL中模拟模态对话框?
- Guzz源码分析(二) guzz解析guzz.xml
- 如何在带有PostgreSQL的tryCatch中使用dbGetQuery?
- 无法找到依赖项com.google.android.gms:play-services-ads
- PostgreSQL 9.5:将间隔转换为INTO毫秒