我无法在下面的代码中找出“Indices.Iterator.Element == Index”的目的/含义
extension Collection where Indices.Iterator.Element == Index { /// Returns the element at the specified index iff it is within bounds,otherwise nil. subscript (safe index: Index) -> Generator.Element? { return indices.contains(index) ? self[index] : nil } }
通用约束语法,其中T == U表示类型T必须与类型U的类型相同.
让我们先做一个更简单的例子:
protocol GenericProtocol { associatedtype T associatedtype U } extension GenericProtocol where T == U { func foo() {} } class ConcreteClassA: GenericProtocol { typealias T = Int typealias U = Float } class ConcreteClassB: GenericProtocol { typealias T = Int typealias U = Int } let a = ConcreteClassA() let b = ConcreteClassB()
现在哪一个,a或b有成员foo?答案是b.
由于扩展的泛型约束表明T和U必须是相同的类型,因此扩展仅应用于ConcreteClassB,因为它的T和U都是Int.
现在回到你的代码.
在您的代码中,您说Indices.Iterator.Element必须与Index类型相同.让我们分别说明这两种类型.
指数是房地产指数的类型.所以Indices.Iterator.Element是集合的每个索引的类型.另一方面,索引是可以放入集合下标的值的类型.这种约束似乎过多,但实际上并非如此.我想不出约束不正确的类型的例子.但是你可以从理论上创造出这样一种类型.这就是约束存在的原因.
如果没有约束,则无法编译:
indices.contains(index)
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。