What does it mean "A collection where Indices.Iterator.Element == Index"

I could not understand the purpose / value of "Indices.Iterator.Element == Index" in the following code

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
    }
}
+4
source share
2 answers

The general constraint syntax where T == Usays that the type Tmust be of the same type as the type U.

First make a simpler example:

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()

Now which one, aor bhas a member foo? The answer b.

Since the total expansion limit adds that T, and Ushould be of the same type, the extension applies only to ConcreteClassB, because it Tand Uare Int.

Get back to your code now.

, Indices.Iterator.Element , Index. , .

Indices - Indices. , Indices.Iterator.Element - . Index , , . , . , . . .

, :

indices.contains(index)
+6

contains(_:) indices ( indices), index ( index). - indices , index.

, , , .

Array . indices CountableRange<Int>, index - Int. , , CountableRange<Int> (CountableRange<Int>.Iterator.Element) index Int.

+1

Source: https://habr.com/ru/post/1665287/


All Articles