提问人:ximmyxiao 提问时间:11/17/2023 最后编辑:ximmyxiao 更新时间:11/17/2023 访问量:48
为什么要在 Swift RandomAccessCollection 协议中重新定义 Element 类型?
Why redefine the Element type in Swift RandomAccessCollection protocol?
问:
从源代码
public protocol RandomAccessCollection<Element> : BidirectionalCollection where Self.Indices : RandomAccessCollection, Self.SubSequence : RandomAccessCollection {
associatedtype Element
我们可以看到定义了 to associatedtype。这种重新定义的含义是什么?RandomAccessCollection
Element
而Array是符合这个协议的。来自 Array 的源代码RandomAccessCollection
@frozen public struct Array<Element> {
...
}
也会有一个。Element
这 3 个元素之间有什么联系吗?
答:
RandomAccessCollection
不需要重新声明 from。删除声明不会破坏任何内容或向代码添加任何新功能。Element
BidirectionalCollection
protocol Foo<T> {
associatedtype T
}
protocol Bar<T>: Foo {
associatedtype T
}
编译为与以下内容完全相同的内容:
protocol Foo<T> {
associatedtype T
}
protocol Bar<T>: Foo {
}
在 godbolt.org 试试这个!
我能看到的唯一区别是生成的文档。通过重新定义 ,RandomAccessCollection.Element 和 BidirectionalCollection.Element
有单独的页面,直接从 和 的页面链接。Element
RandomAccessCollection
BidirectionalCollection
如果不重新声明,则不太明显具有关联类型,因为您必须转到“继承自”部分并转到声明的协议才能看到它确实具有关联类型。Element
RandomAccessCollection
Element
Element
Element
也就是说,你可以争辩说,你可以通过在其声明中看到它的主要关联类型来立即推断出具有关联类型:RandomAccessCollection
Element
Element
protocol RandomAccessCollection<Element>
但是在旧版本的 Swift 中并不存在主要的关联类型,因此作者最初这样做仍然是有道理的。此外,重新声明的不仅仅是 .还有、、等。RandomAccessCollection
Element
Index
SubSequence
通过重新声明关联的类型,在阅读文档时,协议需要什么类型一目了然。
此外,还可以在每个关联的类型声明上编写不同的文档文本。
protocol Foo<T> {
/// something describing T...
associatedtype T
}
protocol Bar<T>: Foo {
/// something describing T that is more specific to Bar...
associatedtype T
}
至于 in ,这是一个泛型类型参数,实现了 (和许多其他协议)的相关类型要求。它本身不是关联的类型声明。Element
Array<Element>
RandomAccessCollection
评论
Element
RandomAccessCollection
Element
Array
C.Element
C
评论