How to fully define relationships between associated Types in Swift?

I have the following setup in order to define a graph (and subgraphs, aka Clusters):

public protocol Node {
    associatedtype C: Cluster where C.N == Self
}

public protocol Edge {
    associatedtype N: Node
}

public protocol Cluster {
    associatedtype N: Node where N.C == Self
    associatedtype C: Cluster where C.N == N, C == Self
}

public protocol Graph {
    associatedtype N: Node where N.C == C
    associatedtype E: Edge where E.N == N
    associatedtype C: Cluster where C.N == N
}

My problem is that I cannot define on the Graph two of the constraints. The Swift compiler (at time of writing part of Xcode 11.4.1 gives the following error messages.
The constraint of N cannot be created because "'C' is not a member type of 'Self.N'"
The constraint of C cannot be created because "'N' is not a member type of 'Self.C'"

enter image description here

Why?

Dunno why either, but since you just keep using == somewhat circularly and redundantly, how about:

public protocol Node {
    associatedtype C: Cluster where C.N == Self
}

public protocol Edge {
    associatedtype N: Node
}

public protocol Cluster {
    associatedtype N: Node where N.C == Self
}

public protocol Graph {
    associatedtype E: Edge
    typealias N = E.N
    typealias C = N.C
}

That works like a charm. Thank you!

Terms of Service

Privacy Policy

Cookie Policy