Fully specialized protocol still has "Self or associated type requirements"

I can never understand why only one of the two code fragments below is valid and the other is a victim of the dreaded "Protocol 'Specialized' can only be used as a generic constraint because it has Self or associated type requirements". Can someone enlighten me? I think many other languages (C++ I'm looking at you) support this just fine.

// This is fine
protocol Base
{
    typealias Document = Data
    func saveDocument(_ document: Document)
}

protocol Specialized: Base
{
    func saveDocument(_ document: Document)
}

func saveSpecialized(_ specialized: Specialized)
{
    specialized.saveDocument(Data())
}


// This is not fine
protocol Base
{
    associatedtype Document
    func saveDocument(_ document: Document)
}

protocol Specialized: Base where Document == Data
{
    func saveDocument(_ document: Document)
}

func saveSpecialized(_ specialized: Specialized)
{
    specialized.saveDocument(Data())
}

You might want to read this topic: https://forums.swift.org/t/lifting-the-self-or-associated-type-constraint-on-existentials

This precise issue has been discussed in this thread:

@suyashsrijan, it would be nice if when the Self/associatedtype constraint is lifted, requirements like saveDocument above are accessible!

2 Likes

AIUI, Document here is just a plain-ol' type alias; the syntax is not an alternate declaration of a customization point. Document is fixed to be Data for every conforming type. This version of Base has only one customization point, and every type attached to that method is fixed.

In the second example, Document is a customization point, and therefore may change between conforming types, thus the error for the second version of Base being limited to a generic constraint.

I understand that part, but Document is no longer a customization point after the type has been completely specified in the Specialized protocol. I.e. at compile time all types are known (and fixed) in this case.

Thanks, I've been trying to for a few years :) Some progress in that general direction would be much appreciated, I keep bumping into similar issues for what I would think are quite common use cases.

Terms of Service

Privacy Policy

Cookie Policy