首页 > 解决方案 > 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
    }
}

标签: swiftgenerics

解决方案


Fetcher需要一个T类型,即符合的特定类型Itemable

因此,例如,如果您有一个 type Foo: Itemable,则Fetcher<Foo, ...>希望使用Foos - not any Itemable, like AnotherFoo: Itemable- but only Foo

然而s 对他们的财产P没有这样的限制—— and和其他东西都可以在.itemsFooAnotherFooitems

因此,您基本上是在尝试执行以下操作:

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
    }
}

推荐阅读