You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何实现Collection协议的index(after:)方法使集合反向遍历

实现自定义Collection的反向遍历

要让你的SimpleCollection遍历输出为5、4、3、2、1,需要调整startIndex、endIndex和index(after:)方法的实现,具体修改如下:

修改要点

  • startIndex:设置为数组最后一个元素的索引(原数组endIndex的前一个位置)
  • endIndex:设置为数组的起始索引(遍历到该位置时停止)
  • index(after:):返回当前索引的前一个索引,实现反向步进

修改后的完整代码

struct SimpleCollection: Collection {
    var numbers = [1, 2, 3, 4, 5]

    var startIndex: Int { numbers.index(before: numbers.endIndex) }
    var endIndex: Int { numbers.startIndex }

    subscript(index: Int) -> Int {
        return numbers[index]
    }

    func index(after i: Int) -> Int {
        return numbers.index(before: i)
    }
}

测试验证

使用原测试代码运行:

let test = SimpleCollection();
for items in test{
    print(items)
}

输出结果为:

5
4
3
2
1

内容的提问来源于stack exchange,提问作者koshe1ca

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.25 08:13:09