2017-05-19 89 views
-1

我有一個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"] 
+0

正在做作業嗎?大聲笑,爲什麼不循環出發數組,獲取每個值,並將其用作字典的「關鍵字」,以提取日期名稱,您將放入新數組中。 – Pochi

+0

我試過的循環沒有產生結果。你能舉一個你的意思嗎? – ruffdrum

+0

@ruffdrum難道你不認爲它只是單行代碼'let resultArray = depatureDay.flatMap {dayDictionary [$ 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) 
+0

完美。這是一個更大問題的一部分,我試圖將其分解爲儘可能簡單。謝謝你的幫助。 – ruffdrum

相關問題