【问题标题】:Issue with protocol conformance in Swift using associatedtypeSwift 中使用关联类型的协议一致性问题
【发布时间】: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) {
         ^

关于该问题的解决方案(如果存在)有什么建议吗?

【问题讨论】:

    标签: swift generics protocols


    【解决方案1】:

    您应该像这样定义您的类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 不是唯一可以采用@987654329 的结构@协议。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-07-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多