英文:
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] }
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论