0

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.

Tomas Ivan
  • 2,212
  • 2
  • 21
  • 34
  • 1
    A `typealias` must be a concrete type, not a protocol. In this case `T` is not a generic. – vadian Dec 10 '20 at 12:25
  • 2
    [Protocols don't conform to themselves](https://stackoverflow.com/a/43408193/5133585), so you can't use `DocumentTemplate` as the type for `T` in `UniversalCollectable`. – Sweeper Dec 10 '20 at 12:27
  • But when I remove `: DocumentTemplate` from associatedtype then I'm available to use protocol in typealias. Or I missing something oblivious? – Tomas Ivan Dec 10 '20 at 12:31
  • 1
    Read the answer I linked. What you are trying to do (`typealias T = DocumentTemplate`) is "unsound" in general. – Sweeper Dec 10 '20 at 12:34

0 Answers0