gpt4 book ai didi

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

转载 作者:搜寻专家 更新时间:2023-10-30 22:29:27 24 4
gpt4 key购买 nike

我无法弄清楚以下代码中“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
}
}

最佳答案

通用约束语法 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()

现在 ab 中的哪一个有成员 foo?答案是b

由于扩展的通用约束规定 TU 必须是同一类型,因此扩展仅应用于 ConcreteClassB,因为它的 TU 都是 Int

现在回到您的代码。

在您的代码中,您说 Indices.Iterator.Element 必须与 Index 的类型相同。我们先来了解一下这两种类型分别是什么。

Indices 是属性 indices 的类型。所以 Indices.Iterator.Element 是集合中每个索引的类型。另一方面,Index 是可以放入集合下标的值类型。这种限制看似过分,但实际上并非如此。我想不出约束不正确的类型示例。但是理论上您可以创建这样的类型。这就是约束存在的原因。

如果约束不存在,这将无法编译:

indices.contains(index)

关于swift - "Collection where Indices.Iterator.Element == Index"是什么意思,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41391043/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com