ios - 如何根据 Swift 中的条件更改数组值?
问题描述
我有这样的数组
var country = ["America","Germany","China"]
我的需要是这个阵列是否有美国
我想让它变成“美国”
希望这样的结果
["US","Europe","Asia"]
不要使用country[0] = "US"
因为每次的数组顺序都不一样
我给的使用条件
我应该怎么做 ?
解决方案
创建一个字典,其中包含国家/地区的字符串需要替换的内容。
let countriesToRegions = ["America": "US", "Germany": "Europe", "China": "Asia"]
然后当你需要将国家转换为地区时,你可以在字典中查找它们。
var countries = ["America", "Germany", "China"]
let regions = countries.map { country in
countriesToRegions[country] ?? country
}
最后一点?? country
,是处理该国家不在countriesToRegions
字典中的可能性。
推荐阅读
- java - 如何使用spring websocket向自定义用户发送自定义消息?
- c - C以纳秒精度获取系统时间
- android - 将 RecyclerView 单击的项目移动到顶部
- typescript - 需要 JSON 文件并转换为接口以验证所有字段是否存在
- javascript - 如何使用 Javascript 在我的 HTML 中添加变量
- elasticsearch - 如何在elasticsearch中进行连接查询?
- python - 如何获取通过 pandas 创建的直方图的 bin 范围
- mysql - 如何限制 MySQL general_log 文件大小?
- php - PHP - 加载 XML/修改/保存的函数
- dialogflow-es - 如何使用 facebook 循环在 Dialogflow 中制作自定义有效负载,返回到先前的意图?