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

Swift中如何简化城市字符串比对查询距离的冗余代码

代码优化方案

方案1:嵌套字典实现(更推荐,无需循环,扩展性更强)

不需要定义零散的距离变量,也不需要写大量if-else判断,直接用嵌套字典存储城市间的距离映射,查询时直接通过键值读取即可,同时会自动处理城市选择顺序的问题(A到B和B到A的距离一致不用重复存储)。
代码实现如下:

// 存储所有城市对的距离
let distanceMap: [String: [String: Int]] = [
    "A": ["B": 423, "C": 1439, "D": 1122],
    "B": ["C": 890, "D": 765],
    "C": ["D": 320]
    // 新增城市只需要补充对应键值对即可
]

// 仅需几行代码完成距离查询
guard let city1 = passedCity.text, let city2 = passedCity2.text, city1 != city2 else {
    result.text = "请选择两个不同的城市"
    return
}
// 支持正反顺序查询
if let distance = distanceMap[city1]?[city2] ?? distanceMap[city2]?[city1] {
    result.text = "\(distance) km"
} else {
    result.text = "未查询到对应距离数据"
}

方案2:for-in循环实现(符合你要求的循环逻辑)

如果需要用for-in循环实现,可以通过城市索引匹配二维距离矩阵的方式完成查询:

// 原有城市数组,索引对应距离矩阵的下标
let cities = ["A","B","C","D"]
// 二维距离矩阵,distanceMatrix[i][j] 对应cities[i]到cities[j]的距离
let distanceMatrix = [
    [0, 423, 1439, 1122],
    [423, 0, 890, 765],
    [1439, 890, 0, 320],
    [1122, 765, 320, 0]
]

// for-in循环匹配两个城市的索引
var index1: Int?
var index2: Int?
for (offset, city) in cities.enumerated() {
    if city == passedCity.text {
        index1 = offset
    }
    if city == passedCity2.text {
        index2 = offset
    }
}

// 输出结果
if let i = index1, let j = index2, i != j {
    result.text = "\(distanceMatrix[i][j]) km"
} else {
    result.text = "请选择两个有效的不同城市"
}

注意该方案需要保证新增城市时,城市数组的顺序和距离矩阵的下标严格对应。


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

相关产品推荐
方舟 Agent Plan

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

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