Swift编程:扩展、协议与通用类型的深入探索
1. 关联类型的 where 子句
从Swift 4开始,泛型协议或其关联类型可以使用 where 子句,其主要作用是减少关联类型链的长度。例如, Sequence 泛型协议有一个关联类型 Iterator ,它必须遵循 IteratorProtocol ,而 IteratorProtocol 又有一个关联类型 Element 。在Swift 4之前,Swift头文件中经常需要使用 where 子句来约束类型为序列的 Iterator.Element 。而在Swift 4及以后,引入关联类型 where 子句后, Sequence 本身可以有一个 Element 关联类型,它就是 Iterator.Element ,代码如下:
protocol Sequence {
associatedtype Element where Self.Element == Self.Iterator.Element
// ...
}
这样,在Swift头文件中,原来的 Iterator.Element 现在可以直接写成 Elemen
超级会员免费看
订阅专栏 解锁全文
61

被折叠的 条评论
为什么被折叠?



