如何在Swift中完全定义关联Types之间的关系?

问题描述 投票:1回答:1

我有以下设置,以便定义一个图(和子图,也就是簇)。

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
}

我的问题是,我不能在图上定义两个约束条件。Swift编译器(在编写Xcode 11.4.1的一部分时,给出了以下错误信息。"N的约束不能被创建,因为"'C'不是'Self.N'的成员类型""C的约束不能被创建,因为"'N'不是'Self.C'的成员类型"。

enter image description here

为什么呢?

swift constraints associated-types
1个回答
1
投票

我在Swift论坛上发布了同样的问题,并得到了Lantua的快速回复 (https:/forums.swift.orguLantuasummary)

将图形重新定义为

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

奏效

© www.soinside.com 2019 - 2024. All rights reserved.