generics - Issue with protocol conformance in Swift using associatedtype -


i cannot make classes compliant protocols use associatedtype. in playground, i've typed brief , simple example show issue: producer produces itemtype compliant items , consumer which consumes them. follows:

protocol itemtype { }  protocol producer: class {     associatedtype t: itemtype     func registerconsumer<c: consumer c.t == t>(consumer: c) }  protocol consumer: class {     associatedtype t: itemtype     func consume<p: producer 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) producer \(producer)")     } } 

xcode warns me following errors:

playground execution failed: myplaygroundyeye.playground:14:7: error: type 'dummyproducer' not conform 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' not conform protocol 'consumer' class dummyconsumer: consumer {       ^ myplaygroundyeye.playground:9:10: note: protocol requires function 'consume(_:item:)' type '<p> (p, item: emptyitem) -> ()' (aka '<τ_1_0> (τ_1_0, item: emptyitem) -> ()')     func consume<p: producer 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) {          ^ 

any suggestions solution (if exists) of issue?

you should define classes dummyproducer , dummyconsumer this:

class dummyproducer: producer {     typealias t = emptyitem      func registerconsumer<c: consumer c.t == t>(consumer: c) {      } }  class dummyconsumer: consumer {     typealias t = emptyitem      func consume<p: producer p.t == t>(producer: p, item: t) {      } } 

since strictly specified associatedtype t itemtype in protocol definition, weren't able use emptyitem in classes because emptyitem not structure can adopt itemtype protocol.


Comments

Popular posts from this blog

java - Jasper subreport showing only one entry from the JSON data source when embedded in the Title band -

serialization - Convert Any type in scala to Array[Byte] and back -

SonarQube Plugin for Jenkins does not find SonarQube Scanner executable -