gpt4 book ai didi

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

转载 作者:搜寻专家 更新时间:2023-10-30 23:01:21 25 4
gpt4 key购买 nike

对于给定的泛型函数

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 接受一个generic 参数,那么再次投稿:

anotherFunction(myGenericFunction() as Bool)

另一种方法是将类型作为参数传递相反:

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

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

关于swift - 在 swift 中设置通用 T 返回的类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39966142/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com