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

Swift中满足特定条件时将数组元素索引+1的实现方法求助

Swift:根据条件切换数组元素为下一个索引值

针对你的需求,这里提供几种实用的实现方式,适配不同场景:

方案1:直接赋值固定索引(最简单直观)

如果你的location数组结构固定,直接指定目标索引即可:

if arrivingLeft {    
    arrivingCity = [location[1], location[3], location[5]]
}

优点:代码一目了然,新手易理解;缺点:如果location后续增删元素,需要手动更新索引。

方案2:通过原元素匹配索引(灵活适配动态元素)

如果arrivingCity的元素可能动态变化,可先找到元素在location中的索引,再取索引+1的元素:

if arrivingLeft {    
    arrivingCity = arrivingCity.compactMap { city in
        guard let idx = location.firstIndex(of: city) else {
            return nil // 若元素不在location中,过滤掉该元素
        }
        return location[idx + 1]
    }
}

优点:无需硬编码索引,自动对应下一个元素;缺点:依赖元素在location中的唯一性(如果有重复元素,firstIndex会取第一个匹配项)。

方案3:利用数组结构生成目标元素(扩展性最佳)

观察到location是成对的right/left结构,可直接生成所有奇数索引的元素:

if arrivingLeft {    
    arrivingCity = stride(from: 1, to: location.count, by: 2).map { location[$0] }
}

优点:即使location添加新的成对元素,代码无需修改;缺点:仅适用于这种两两配对的数组结构。

完整示例代码

var location = [
    "City Center right",
    "City Center left",
    "City District right",
    "City District left",
    "Periphery right",
    "Periphery left"]

var arrivingCity = [location[0], location[2], location[4]]

var arrivingLeft = true

if arrivingLeft {    
    // 选择任意一种方案替换下面的代码
    arrivingCity = [location[1], location[3], location[5]]
}

print(arrivingCity) // 输出:["City Center left", "City District left", "Periphery left"]

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.22 02:50:26