I struggle with associatedtype to make it work as I want. So ask for clarification and explanation why example below doesn't work. Bellow example is executable in playground.
I have this structures Foo and Bar where both implement DocumentTemplate.
public protocol DocumentTemplate {
}
public struct Foo: DocumentTemplate {
public var _id: String!
}
public struct Bar: DocumentTemplate {
public var _name: String!
}
I have generic protocol DocumentCollectable require type T inherit from DocumentTemplate, and two implementations of UniversalCollectable depends on DocumentTemplate and FooCollectable depends on Foo.
public protocol DocumentCollectable {
//type T must implement protocol DocumentTemplate
//error workaround remove ': DocumentTemplate'
associatedtype T: DocumentTemplate
func collect(_ d: T)
}
public class UniversalCollectable: DocumentCollectable {
public typealias T = DocumentTemplate //error
public func collect(_ d: T) {
print("universal done")
}
}
public class FooCollectable: DocumentCollectable {
public typealias T = Foo
public func collect(_ d: T) {
print("foo done")
}
}
When I execute this:
let u = UniversalCollectable()
u.collect(Foo())
u.collect(Bar())
let f = FooCollectable()
f.collect(Foo())
I'll get error message
error: type 'UniversalCollectable' does not conform to protocol 'DocumentCollectable'
But if I make change to associatedtype T not inherit from DocumentTemplate, then everything run smooth. But I need type T to inherit from DocumentTemplate.