gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 17:10:26 26 4
gpt4 key购买 nike

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 的重新声明在结构中我得到一个编译错误,与下标有关:

Unsupported recursion for reference to type alias 'D' of type'UndirectedGraph'


为什么会这样?什么递归???

最佳答案

我不确定什么是递归,但你应该避免在 protocol extensions 中声明类型别名。并改用相同类型的约束:

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 }
}
}

可能就够了。

关于swift - 符合协议(protocol)时类型别名声明的冗余重复(第 2 部分),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64349026/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com