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

Swift 5视图中用ForEach遍历数组时如何设置索引偏移及循环次数?

解决方案

方案1:统一添加全局固定偏移

如果只是需要给原有索引统一加固定偏移值,直接在闭包内对index做运算即可,不需要修改遍历的数据源:

let offset = 5
ForEach(cities.indices, id: \.self) { index in
    let actualIndex = index + offset
    // 直接使用actualIndex处理业务逻辑即可
}

如果你的需求是遍历次数超过数组本身长度(比如数组长度10要循环15次),可以直接遍历你需要的总次数范围,访问数组时用取模运算避免越界:

let totalLoopCount = 15
let offset = 5
ForEach(0..<totalLoopCount, id: \.self) { index in
    let actualIndex = (index + offset) % cities.count
    let city = cities[actualIndex]
    // 业务逻辑
}

方案2:按固定步长递增遍历索引

如果你需要索引每次按指定步长(比如+5)递增,直接用stride生成遍历序列即可,完全基于数组原生indices属性实现,不需要手动构造额外数组:

// 从数组索引最小值开始,到最大值结束,步长为5
ForEach(Array(stride(from: cities.startIndex, to: cities.endIndex, by: 5)), id: \.self) { index in
    // 这里的index就是0、5、10...按步长递增的结果
}

如果需要自定义遍历的起止范围,调整stride的from和to参数即可,比如要遍历15次、每次+5:

ForEach(Array(stride(from: 0, to: 15, by: 5)), id: \.self) { index in
    let actualIndex = index % cities.count
    let city = cities[actualIndex]
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.01 07:15:01