使用关联类型

时间:2016-09-07 12:12:19

标签: swift generics protocols

我无法使类符合使用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) {
         ^

有关该问题的解决方案(如果存在)的任何建议?

1 个答案:

答案 0 :(得分:3)

您应该像这样定义您的课程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,因为{{1 }}不是唯一可以采用EmptyItem协议的结构。

相关问题