如何实现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
相关产品推荐
相关产品推荐

