泛型类和子类的数组



我很难理解泛型。我想要的是有一个泛型类数组,每个泛型类都有自己的关联类型,并相应地调用一个函数。它看起来像这样:

class SomeGenericClass<U> {
func addCallback(callback: (U)->() ) { ... }
}
var array: [SomeGenericClass] // compile error

最后一行产生错误,所以我发现我需要有一个超类。我尝试了这样的事情:

class SuperClass {
func addCallback<V>(callback: (V)->() ) { ... }
}
class SomeGenericClass<U> {
func addCallback<V: U>(callback: (V)->() ) { ... } // compile error
}
var array: [SuperClass] // no compile error

这将产生错误Type 'V' constrained to non-protocol, non-class type 'U'

基本上我希望能够做到:

array.append(SomeGenericClass<UIImage>()) // array[0]
array.append(SomeGenericClass<Int>()) // array[1]
// Since array[0] is effectively of type SomeGenericClass<UIImage>, the compiler should understand that the close added if of type (UIImage)->(), and therefore that value is of type UIImage
array[0].addCallback { value in
someImageView.image = value
}

在这种情况下,使用超类是正确的方法吗?应该如何实施?

我通过将数组成员存储在它们自己的变量中来解决此问题。也就是说,而不是像这样定义我的数组:

lazy var array: [SuperClass] = [
SomeGenericClass<UIImage>(),
SomeGenericClass<Int>(),
//etc...
]

我是这样定义的:

lazy var genericFirst: SomeGenericClass<UIImage> = SomeGenericClass<UIImage>()
lazy var genericSecond: SomeGenericClass<Int> = SomeGenericClass<Int>()
// etc...
lazy var array: [SuperClass] = [
genericFirst,
genericSecond,
//etc...
]

这样,我可以像这样访问我想要的泛型:

genericFirst.addCallback { value in
// value is indeed of type UIImage
someImageView.image = value
}

最新更新