2017-05-28 20 views
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」

這究竟是爲什麼。我正在返回正確的值。

謝謝,我希望我找到一個很好的解決方案。

回答

1

您的test()函數基本上承諾「我將返回一個ParsableGeneric<T>對象的任何T這是一個Parsable」。但是,該實施僅返回ParsableIntNew,即僅當TIntParse時才起作用。

想象一下,當你也有一個BoolParse: Parsable會發生什麼,並且編譯器得出結論,當你撥打test()TBoolParse。即使功能返回類型爲ParsableGeneric<BoolParse>,函數仍然會返回ParsableGeneric<IntParse>

+0

嘿thm,謝謝你的貢獻。在這種情況下你打算做什麼?使用一些枚舉來包裝值?我不想做的是返回Any,因爲不是類型安全的。 –

+0

不客氣。你的「測試」功能應該做什麼? – thm

+0

我在這個函數之外有一個映射,這個映射調用一個返回ParsableGeneric的函數。然後我可以調用test()。parse()。parseString()並獲取將數組轉換爲此通用值的值。如果我在測試函數中返回Any,然後在測試函數中直接返回test()。parse()。parseString() –

相關問題