迭代String的UTF8View时显示不同的类型

时间:2017-03-29 08:09:02

标签: swift string unicode utf-8

我正在学习swift中的字符串。我有两个版本的相同代码

enter image description here

enter image description here

for for循环中的变量假设具有相同的类型,但正如您所看到的,类型实际上是不同的?

我必须在这里遗漏一些东西,但似乎无法弄明白。

1 个答案:

答案 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具有Iterator.Element Collection相同的类型来满足此关联类型>

subscript(position: Index) -> Iterator.Element { get }

要求。因此,当符合Collection时,编译器默认会推导出Iterator.Element == _Element

使用String.UTF8View,它实现Collection Iterator.Element类型UTF8.CodeUnit(又名。UInt8)。因此,String.UTF8View._ElementString.UTF8View.Iterator.ElementUTF8.CodeUnitUInt8类型都是相同的。

您可以通过比较元类型值轻松验证这一点:

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