簡體   English   中英

使用關聯類型在Swift中協議一致性問題

[英]Issue with protocol conformance in Swift using associatedtype

我不能使類符合使用associatedtype協議。 在Playground中,我輸入了一個簡短而簡單的示例來顯示該問題:生成ItemType兼容項的生產者和使用它們的消費者。 它跟隨:

protocol ItemType { }

protocol Producer: class {
    associatedtype T: ItemType
    func registerConsumer<C: Consumer where C.T == T>(consumer: C)
}

protocol Consumer: class {
    associatedtype T: ItemType
    func consume<P: Producer where P.T == T>(producer: P, item: T)
}

struct EmptyItem: ItemType { }

class DummyProducer: Producer {
    var consumer: DummyConsumer?

    func registerConsumer(consumer: DummyConsumer) {
        self.consumer = consumer
    }
}

class DummyConsumer: Consumer {
    func consume(producer: DummyProducer, item: EmptyItem) {
        print("Received \(item) from producer \(producer)")
    }
}

Xcode警告我以下錯誤:

Playground execution failed: MyPlaygroundYeYe.playground:14:7: error: type 'DummyProducer' does not conform to protocol 'Producer'
class DummyProducer: Producer {
      ^
MyPlaygroundYeYe.playground:3:20: note: protocol requires nested type 'T'
    associatedtype T: ItemType
                   ^
MyPlaygroundYeYe.playground:22:7: error: type 'DummyConsumer' does not conform to protocol 'Consumer'
class DummyConsumer: Consumer {
      ^
MyPlaygroundYeYe.playground:9:10: note: protocol requires function 'consume(_:item:)' with type '<P> (P, item: EmptyItem) -> ()' (aka '<τ_1_0> (τ_1_0, item: EmptyItem) -> ()')
    func consume<P: Producer where P.T == T>(producer: P, item: T)
         ^
MyPlaygroundYeYe.playground:23:10: note: candidate has non-matching type '(DummyProducer, item: EmptyItem) -> ()' [with T = EmptyItem]
    func consume(producer: DummyProducer, item: EmptyItem) {
         ^

關於該問題的解決方案(如果存在)的任何建議?

你應該像這樣定義你的DummyProducerDummyConsumer類:

class DummyProducer: Producer {
    typealias T = EmptyItem

    func registerConsumer<C: Consumer where C.T == T>(consumer: C) {

    }
}

class DummyConsumer: Consumer {
    typealias T = EmptyItem

    func consume<P: Producer where P.T == T>(producer: P, item: T) {

    }
}

由於您在協議定義中嚴格指定了associatedType TItemType ,因此您無法在類中僅使用EmptyItem ,因為EmptyItem不是唯一可以采用ItemType協議的結構。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM