2017-03-06 73 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) 
}