1
我無法使類符合使用associatedtype
的協議。在Playground中,我輸入了一個簡短而簡單的例子來說明這個問題:生產者生產ItemType
兼容物品和消費者。它遵循:使用關聯類型在Swift中使用協議一致性的問題
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) {
^
任何建議,關於解決方案(如果存在)這個問題的?