目录

泛型下标

优质
小牛编辑
140浏览
2023-12-01

泛型下标

  • 下标可以是泛型, 它们可以包含泛型where分句. 你可以在subscript后用尖括号来写类型占位符, 你还可以在下标代码块花括号前写泛型where分句.

e.g.

protocol Container {
    associatedtype ItemType
    mutating func append(_ item: ItemType)
    var count: Int { get }
    subscript(i: Int) -> ItemType { get }
}

extension Container {
    subscript<Indices: Sequence>(indices: Indices) -> [ItemType]
        where Indices.Iterator.Element == Int {
            var result = [ItemType]()

            for index in indices {
                result.append(self[index])
            }
            return result
    }
}
  • 在尖括号中的泛型形式参数Indices必须是遵循标准库中Sequence协议的某类型;

  • 下标接收单个形式参数, indices, 他是一个Indices类型的实例

  • 泛型where分句要求序列的遍历器必须遍历Int类型的元素. 这就保证了序列中的索引都是作为容器索引的相同类型.

  • 合在一起, 这些限定意味着传入的indices形式参数是一个整数的序列.