首页 > 解决方案 > 如何根据 Swift 中的条件更改数组值?

问题描述

我有这样的数组

var country = ["America","Germany","China"]

我的需要是这个阵列是否有美国

我想让它变成“美国”

希望这样的结果

["US","Europe","Asia"]

不要使用country[0] = "US"

因为每次的数组顺序都不一样

我给的使用条件

我应该怎么做 ?

标签: iosswift

解决方案


创建一个字典,其中包含国家/地区的字符串需要替换的内容。

let countriesToRegions = ["America": "US", "Germany": "Europe", "China": "Asia"]

然后当你需要将国家转换为地区时,你可以在字典中查找它们。

var countries = ["America", "Germany", "China"]

let regions = countries.map { country in
    countriesToRegions[country] ?? country
}

最后一点?? country,是处理该国家不在countriesToRegions字典中的可能性。


推荐阅读