在Swift中,如果满足特定条件,可以使数组的索引加1。

huangapple go评论66阅读模式
英文:

Make an array add +1 to index if a specific condition is met in swift

问题

Sure, here's the translated code portion:

我对编程一般不太了解,但是开始使用Swift
在谷歌搜索中找不到答案,还查看了苹果文档,但是一无所获。
所以我尝试做的是,当满足特定条件时,使数组显示下一个项目,例如它之前是索引0,但现在必须显示索引1处的项目;如果它是2,就要显示索引3处的项目,依此类推。

var location = [
    "市中心右侧",
    "市中心左侧",
    "城市区右侧",
    "城市区左侧",
    "外围右侧",
    "外围左侧"]

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

var arrivingLeft = true

if arrivingLeft == true {    
    arrivingCity = // 在这里应该更改索引+1,以显示为 [location[1], location[3], location[5]]
}

Please note that I've translated the comments and code comments as well.

英文:

I am new to new to programming in general, but started with Swift
Could not find my answer searching google, also looked at apple documentation, but I was getting nowhere.
So what I am trying to do, is to make an array display the next item in it when a specific condition is met, for example it was and index 0 but now it has to show the one that was at index 1; if it where 2, to show the one at index 3, and so on.

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 == true {    
    arrivingCity = // here is should change the index +1 so it will show as// [location[1], location[3], location[5]]
}

答案1

得分: -2

为了实现可扩展的解决方案,您应该维护位置的索引。

var location = [
    "市中心右",
    "市中心左",
    "城区右",
    "城区左",
    "郊区右",
    "郊区左"]

// 而不是存储位置,存储它们的索引
var arrivingCityIndexes = [0, 2, 4]

var arrivingLeft = true

if arrivingLeft == true {
    // 将每个索引加一以移动到下一个城市
    arrivingCityIndexes = arrivingCityIndexes.map { $0 + 1 }
}

// 在需要时,将`arrivingCityIndexes`数组映射到到达城市名称的数组
let arrivingCity = arrivingCityIndexes.map { location[$0] }
英文:

For an extensible solution, you should maintain indexes of locations.

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


// Instead of storing locations store its indexes
var arrivingCityIndexes = [0, 2, 4]

var arrivingLeft = true

if arrivingLeft == true {   
     // Increment each index by one to move to the next city
    arrivingCityIndexes = arrivingCityIndexes.map { $0 + 1 }
}

// When required, map the `arrivingCityIndexes` array to an array of arriving city names
let arrivingCity = arrivingCityIndexes.map { location[$0] }

huangapple
  • 本文由 发表于 2023年5月14日 17:36:19
  • 转载请务必保留本文链接:https://go.coder-hub.com/76246775.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定