当符合协议时,类型别名声明的冗余重复(第2部分)


protocol Destinationable: Hashable {
associatedtype D: Hashable
var destination: D { get }
}
protocol Graph {
associatedtype Edge: Destinationable
subscript(node: D) -> Set<Edge>! { get set }
}
extension Graph {
typealias D = Edge.D
}
struct UndirectedGraph<Edge: Destinationable>: Graph {
typealias D = Edge.D // Why should we again declare this typealias!?

private var storage: [D: Set<Edge>]

subscript(node: D) -> Set<Edge>! {
get { storage[node] }
set { storage[node] = newValue }
}
}

这是有效的。但是,如果我在结构中删除typealias D = Edge.D的重新声明,我会得到一个编译错误,与下标有关

不支持递归引用类型的类型别名"D"无方向图">

为什么会发生这种情况?什么递归???

我不确定是什么递归,但您应该避免在协议扩展中声明类型别名,而是使用相同的类型常量:

protocol Destinationable: Hashable {
associatedtype D: Hashable
var destination: D { get }
}
protocol Graph {
associatedtype D
associatedtype Edge: Destinationable where D == Edge.D
subscript(node: D) -> Set<Edge>! { get set }
}
struct UndirectedGraph<Edge: Destinationable>: Graph {
private var storage: [D: Set<Edge>]

subscript(node: Edge.D) -> Set<Edge>! {
get { storage[node] }
set { storage[node] = newValue }
}
}

编译得很好,但在您的情况下:

protocol Destinationable: Hashable {
associatedtype D: Hashable
var destination: D { get }
}
protocol Graph {
associatedtype Edge: Destinationable
subscript(node: Edge.D) -> Set<Edge>! { get set }
}
struct UndirectedGraph<Edge: Destinationable>: Graph {
private var storage: [Edge.D: Set<Edge>]

subscript(node: Edge.D) -> Set<Edge>! {
get { storage[node] }
set { storage[node] = newValue }
}
}

也许就足够了。

最新更新