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 的地方现在可以直接使用 Element </
超级会员免费看
订阅专栏 解锁全文
7

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



