如何根据字典中匹配的值替换数组中的值?

时间:2017-05-19 07:55:58

标签: arrays dictionary swift3

我有一个String数组,例如:

var depatureDay: [String] = ["2", "4", "1", "5"]

我有一本字典

var dayDictionary: [String: String] = [
        "1": "Monday",
        "2": "Tuesday",
        "3": "Wednesday",
        "4": "Thursday",
        "5": "Friday",
        "6": "Saturday",
        "7": "Sunday"]

如何遍历数组以生成数组

["Tuesday", "Thursday", "Monday", "Friday"]

2 个答案:

答案 0 :(得分:0)

这看起来像家庭作业......

var depatureDay: [String] = ["2", "4", "1", "5"]


var dayDictionary: [String: String] = [
    "1": "Monday",
    "2": "Tuesday",
    "3": "Wednesday",
    "4": "Thursday",
    "5": "Friday",
    "6": "Saturday",
    "7": "Sunday"]


var resultArray = [String]()

for dayKey in depatureDay {

    guard let foundDate = dayDictionary[dayKey] else {
        continue
    }

    resultArray.append(foundDate)
}

print(resultArray)

答案 1 :(得分:0)

Swift 5.0中的另一种解决方案:

let result = dayDictionary.filter{ depatureDay.contains($0.key) }.values

print(result)  //"["Thursday","Friday","Tuesday","Monday"]"