2016-07-11 48 views
1

我正在尋找這個最佳的語法:斯威夫特詞典:加入鍵和值轉換爲字符串

 let responseParameters = ["keyA" : "valueA", "keyB" : "valueB"] 
     var responseString = "" 
     for (key, value) in responseParameters { 
      responseString += "\(key):\(value)" 
      if Array(responseParameters.keys).last != key { 
       responseString += "+" 
      } 
     } 
     //responseString: keyA:valueA+keyB:valueB 

喜歡的東西數組joinWithSeparator,使用flatMap或類似的東西。 (學習目的)

回答

8

您可以映射字典中的鍵/值對以將它們轉換爲字符串數組,然後您可以將它們加入+。但請記住,字典是無序的,所以這不會保留輸入順序。

let responseParameters = ["keyA" : "valueA", "keyB" : "valueB"] 

let responseString = responseParameters.map{ "\($0):\($1)" } 
             .joinWithSeparator("+") 
2

字典不是有序集合,因此您必須在訪問鍵值對的「有序版本」之前對鍵進行排序。例如。

let responseParameters = ["keyA" : "valueA", "keyB" : "valueB", "keyC" : "valueC"] 

let responseString = responseParameters 
    .sort { $0.0 < $1.0 } 
    .map { $0 + ":" + $1 } 
    .joinWithSeparator("+") 

print(responseString) // keyA:valueA+keyB:valueB+keyC:valueC