swift - Swift 泛型:如何避免这种奇怪的行为?
问题描述
我遇到了奇怪的行为。也许我做错了,但我不知道。
错误:Cannot assign value of type '[Itemable]' to type '[T]'
protocol Itemable {
var id: Int { get set }
}
protocol Paginatable {
var items: [Itemable] { get set }
}
class Fetcher<T: Itemable, P: Paginatable> {
var items = [T]()
func onReceive(pagination: P) {
items = pagination.items
}
}
解决方案
类Fetcher
需要一个T
类型,即符合的特定类型Itemable
。
因此,例如,如果您有一个 type Foo: Itemable
,则Fetcher<Foo, ...>
希望使用Foo
s - not any Itemable
, like AnotherFoo: Itemable
- but only Foo
。
然而s 对他们的财产P
没有这样的限制—— and和其他东西都可以在.items
Foo
AnotherFoo
items
因此,您基本上是在尝试执行以下操作:
let items: [Itemable] = [...]
let foos: [Foo] = items // error
如果您想限制P
持有与 相同的项目T
,那么您可以执行以下操作:
protocol Itemable {
var id: Int { get set }
}
protocol Paginatable {
associatedtype Item: Itemable
var items: [Item] { get set }
}
class Fetcher<T, P: Paginatable> where P.Item == T {
var items = [T]()
func onReceive(pagination: P) {
items = pagination.items
}
}
推荐阅读
- eclipse - Maven2 安装:缺少工件
- bluetooth - “启用角色切换”(来自链接策略设置)和“允许角色切换”(在 ACL 连接中)之间的区别?蓝牙 BR/EDR/LE
- javascript - 我想根据一个属性对一组对象进行排序。将值推送到具有与其排序相同的属性的第二个属性中
- homebrew - Homebrew - 请求的 URL 已重新调整错误:404
- pytorch - 向量化代码并从 pytorch 代码中删除嵌套循环
- postgresql - count(*) 返回少于实际行数
- python - 如何使用带有 appId 和 processId 异常的 appium 和 python 定位打开的应用程序窗口?
- sql - 在事件发生后的当天找到每种事件类型的平均值
- python - PushShift:从时间范围内抓取提交
- javascript - 之后添加 html-element 的动态函数调用