Swift Dictionary: join key and value into string Swift Dictionary: join key and value into string swift swift

Swift Dictionary: join key and value into string


You can map over key/value pairs in dictionaries to convert them to an Array of Strings, then you can join those with +. But remember, dictionaries are unordered, so this will not preserve the input ordering.

let responseParameters = ["keyA" : "valueA", "keyB" : "valueB"]let responseString = responseParameters.map{ "\($0):\($1)" }                                       .joinWithSeparator("+")


A dictionary is not an ordered collection, so you'll have to sort the keys prior to accessing the "ordered version" of the key-value pairs. E.g.

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


Updated answer for swift 5 :

let responseParameters = ["keyA": "valueA", "keyB": "valueB"]let responseString = responseParameters.map { "\($0):\($1)" }                                   .joined(separator: "+")