什么是"Collection where Indices.Iterator.Element == Index"的意思

Jac*_*cky 5 swift

我无法在下面的代码中找出"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
    }
}
Run Code Online (Sandbox Code Playgroud)

Swe*_*per 8

通用约束语法where 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()
Run Code Online (Sandbox Code Playgroud)

现在哪个,a或者b有会员foo?答案是b.

由于扩展的泛型约束表示T并且U必须是相同的类型,因此扩展仅适用于ConcreteClassB因为它TU它们都是Int.

现在回到你的代码.

在你的代码中,你说它Indices.Iterator.Element必须是相同的类型Index.让我们分别说明这两种类型.

Indices是属性的类型indices.所以Indices.Iterator.Element集合的每个索引的类型也是如此.Index另一方面,是可以放入集合下标的值的类型.这种约束似乎过多,但实际上并非如此.我想不出约束不正确的类型的例子.但是你可以从理论上创造出这样一种类型.这就是约束存在的原因.

如果没有约束,则无法编译:

indices.contains(index)
Run Code Online (Sandbox Code Playgroud)