0
我在swift中遇到了泛型問題。讓我們公開我的代碼。返回Generic在Swift中輸入函數(無法轉換類型爲...的返回表達式)
解析的協議:
protocol Parsable {
associatedtype T
var value: String {get set}
init(value: String)
func parseString() -> T
}
泛型類:
class ParsableIntNew: ParsableGeneric<IntParse> {}
struct IntParse: Parsable {
func parseString() -> Int {
return Int(value)!
}
var value: String
typealias T = Int
}
然後,我有這樣的功能,我想回到一個:
class ParsableGeneric<T: Parsable> {
var value: String
init(v: String) {
value = v
}
func parse() -> T{
return T(value: self.value)
}
}
整型的實現ParsableGeneric類型:
func test<T: Parsable>() -> ParsableGeneric<T> {
let intclass = ParsableIntNew(v: "54")
let number: Int = intclass.parse().parseString()
return intclass
}
但我有在return intclass
(無法轉換類型的返回表達式「ParsableIntNew」錯誤返回類型「ParsableGeneric」
這究竟是爲什麼。我正在返回正確的值。
謝謝,我希望我找到一個很好的解決方案。
嘿thm,謝謝你的貢獻。在這種情況下你打算做什麼?使用一些枚舉來包裝值?我不想做的是返回Any,因爲不是類型安全的。 –
不客氣。你的「測試」功能應該做什麼? – thm
我在這個函數之外有一個映射,這個映射調用一個返回ParsableGeneric的函數。然後我可以調用test()。parse()。parseString()並獲取將數組轉換爲此通用值的值。如果我在測試函數中返回Any,然後在測試函數中直接返回test()。parse()。parseString() –