答案 0 :(得分:2)
这只是一个演示文稿 - _IndexableBase
协议(Collection
internally derives from)声明_Element
associated type作为一致性循环的解决方法:
protocol _IndexableBase {
// ...
// The declaration of _Element and subscript here is a trick used to
// break a cyclic conformance/deduction that Swift can't handle. We
// need something other than a Collection.Iterator.Element that can
// be used as IndexingIterator<T>'s Element. Here we arrange for
// the Collection itself to have an Element type that's deducible from
// its subscript. Ideally we'd like to constrain this Element to be the same
// as Collection.Iterator.Element (see below), but we have no way of
// expressing it today.
associatedtype _Element
// ...
subscript(position: Index) -> _Element { get }
// ...
}
(请注意,这将在recursive protocol constraints实施后全部更改)
实际上,由于Collection
具有
Collection
相同的类型来满足此关联类型>
subscript(position: Index) -> Iterator.Element { get }
要求。因此,当符合Collection
时,编译器默认会推导出Iterator.Element
== _Element
。
使用String.UTF8View
,它实现Collection
Iterator.Element
类型UTF8.CodeUnit
(又名。UInt8
)。因此,String.UTF8View._Element
,String.UTF8View.Iterator.Element
,UTF8.CodeUnit
和UInt8
类型都是相同的。
您可以通过比较元类型值轻松验证这一点:
print(UInt8.self == UTF8.CodeUnit.self) // true
print(UInt8.self == String.UTF8View._Element.self) // true
print(UInt8.self == String.UTF8View.Iterator.Element.self) // true
在这种情况下,Xcode只是选择显示不同类型的别名。虽然在Xcode 8.3 beta 4中,它们都显示为UTF8.CodeUnit
。