2016-09-07 69 views
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) { 
     ^

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

回答

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) { 

    } 
} 

既然你嚴格規定associatedTypeT要在協議定義ItemType,你不能僅僅因爲EmptyItemEmptyItem在使用你的類不是唯一可以採用ItemType協議的結構。