【发布时间】:2017-05-28 17:14:18
【问题描述】:
我对 swift 中的泛型有疑问。让我们公开我的代码。
可解析协议:
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”类型的返回表达式
为什么会这样。我正在返回正确的值。
谢谢,我希望我能找到一个好的解决方案。
【问题讨论】: