arrays - 泛型类和子类的数组
问题描述
我很难理解泛型。我想要的是拥有一组泛型类,每个类都有自己的关联类型,并相应地调用一个函数。它看起来像这样:
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
}
推荐阅读
- python-3.x - 使用 matplotlib 排除 for 循环创建的图例中的图
- java - 2048变更检查方法java
- android - 在 Android 上读取系统文件时权限被拒绝
- javascript - 如何使用正则表达式删除空格、特殊字符和前导数字?
- php - PHP日期时区转换 - 天
- mysql - 计算某个时间段前后存在的值
- binary - -3 + -3 = -2 在二进制补码中
- gmail-addons - 推荐在 gmail 插件中存储安全令牌的方法?
- spring - 没有 UI 的 Spring Boot 招摇文件
- angular - 使用 jsstore 在 Angular 中存储来自 GET 请求的大量数据