【发布时间】:2016-09-07 12:12:19
【问题描述】:
我无法使类符合使用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) {
^
关于该问题的解决方案(如果存在)有什么建议吗?
【问题讨论】: