gpt4 book ai didi

swift - 使用 Swift 在函数中返回泛型类型(无法转换类型的返回表达式...)

转载 作者:行者123 更新时间:2023-11-28 06:19:09 25 4
gpt4 key购买 nike

我对 swift 中的泛型有疑问。让我们公开我的代码。

可解析协议(protocol):

protocol Parsable {
associatedtype T
var value: String {get set}
init(value: String)
func parseString() -> T
}

通用类:

class ParsableGeneric<T: Parsable> {
var value: String
init(v: String) {
value = v
}

func parse() -> T{
return T(value: self.value)
}
}

Int类型的实现:

class ParsableIntNew: ParsableGeneric<IntParse> {}

struct IntParse: Parsable {
func parseString() -> Int {
return Int(value)!
}
var value: String
typealias T = Int
}

然后我有一个这样的函数,我想返回一个 ParsableGeneric 类型:

func test<T: Parsable>() -> ParsableGeneric<T> {
let intclass = ParsableIntNew(v: "54")
let number: Int = intclass.parse().parseString()
return intclass
}

但是我在return intclass 中遇到了错误(无法将“ParsableIntNew”类型的返回表达式转换为“ParsableGeneric”类型

为什么会这样。我正在返回正确的值。

谢谢,我希望我能找到一个好的解决方案。

最佳答案

你的 test()函数基本上 promise “我将为任何 ParsableGeneric<T> 返回一个 T 对象,即 Parsable”。但是,该实现仅返回 ParsableIntNew。 ,即它仅在 T 时有效是IntParse .

想象一下当您还有一个 BoolParse: Parsable 时会发生什么并且编译器得出结论,当您调用 test()TBoolParse .该函数仍会返回 ParsableGeneric<IntParse>。即使在这种情况下函数返回类型是 ParsableGeneric<BoolParse> .

关于swift - 使用 Swift 在函数中返回泛型类型(无法转换类型的返回表达式...),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44225380/

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