swift – “Collection where Indices.Iterator.Element == Inde
发布时间:2020-12-14 02:25:41 所属栏目:百科 来源:网络整理
导读:我无法在下面的代码中找出“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 i
我无法在下面的代码中找出“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) (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |