gpt4 book ai didi

swift - 我可以指定一个类实例可以转换为某种类型吗?

转载 作者:搜寻专家 更新时间:2023-11-01 06:44:01 24 4
gpt4 key购买 nike

假设我有一个泛型类

class Foo<T> { … }

我能以某种方式指定此类的实例可以在赋值中转换为 T 吗?示例:

let foo = Foo<Int>()
func useAnInt(a: Int) {}

let getTheInt: Int = foo
useAnInt(foo)

最佳答案

为什么不直接使用底层类型呢? (类似于@MrBeardsley 的回答)

class Foo<T> {
var t : T

init(t: T) {
self.t = t
}
}


let foo = Foo(t: 3)
func useAnInt(a: Int) {}

let getTheInt: Int = foo.t
useAnInt(foo.t)

关于swift - 我可以指定一个类实例可以转换为某种类型吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32424573/

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