2017-03-06 23 views
1

確定這裏的數組的問題:斯威夫特 - 通用無法追加到超類

說,我們有持有ChildClasses

class ParentClass { 

    var list: [ChildClass<UITableViewCell>] = [] 

    func append<T>(cell: T) where T: UITableViewCell { 
     let child = ChildClass<T>() 
     list.append(child) 
    } 

} 

的陣列和子類的父類,

class ChildClass<T> where T: UITableViewCell { 

    var obj: T! 

} 

兩個類的是通用的類型(T)常是類型的UITableViewCell

現在如果你嘗試建立它,你會得到這個錯誤:

Cannot convert value of type ChildClass< T > to expected argument type ChildClass< UITableViewCell >

但如果T是的UITableViewCell的子類,應該不是能夠到T轉換???
由於事先

+0

密切相關(欺騙?):如何存放Class類型的值在Swift中類型爲\ [String:Class \]的字典中](http://stackoverflow.com/q/38590548/2976878) – Hamish

+0

這真的很難找到這個問題,如果你認爲它是重複的,我同意 –

回答

1

ChildClass<T>不是ChildClass<UITableViewCell>一個子類,即使TUITableViewCell一個子類。

我的答案在這裏提供了什麼差錯,如果建立這樣的協方差的例子:https://stackoverflow.com/a/42615736/3141234

+0

好的,但我怎麼能存儲具有泛型的列表中的不同類型的相同子類的項目? –

+0

您必須將child定義爲'ChildClass ()',並將'cell'賦值給它的'obj'。當然,注意到這會將'cell'上傳爲'UITableViewCell',失去了類型信息。 – Alexander

+0

所以我將失去這些類型信息,並且必須添加額外的投射才能正常工作。以及猜你是對的,無論如何謝謝 –

1

斯威夫特是很嚴格的仿製藥。 ChildClass<UITableViewCell>ChildClass<SomeSubclassOfUITableViewCell>不兼容。

對此的一個解決方法是將ChildClass<SomeSubclassOfUITableViewCell>轉換爲ChildClass<UITableViewCell>,因爲在邏輯上它們應該是兼容的。我還注意到,您沒有使用cell參數,所以也許這是你希望你的方法是:

func append<T>(cell: T) where T: UITableViewCell { 
    let child = ChildClass<UITableViewCell>() 
    child.obj = cell 
    list.append(child) 
}