Swift Dictionary: join key and value into string
Actually, you can use reduce
like: ð
let responseParameters = ["keyA": "valueA", "keyB": "valueB"]
let responseString = responseParameters.reduce("") { $0.isEmpty ? "\($1.key):\($1.value)" : "\($0)+\($1.key):\($1.value)" }
Updated answer for swift 5 :
let responseParameters = ["keyA": "valueA", "keyB": "valueB"]
let responseString = responseParameters.map { "\($0):\($1)" }
.joined(separator: "+")
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
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)" }
.joined(separator: "+")