Convert Swift Dictionary to String
Just use the description
property of CustomStringConvertible
as
Note: Prior to Swift 3 (or perhaps before), CustomStringConvertible
was known as Printable
.
Dictionary to string with custom format:
let dic = ["key1":"value1", "key2":"value2"]
let cookieHeader = (dic.flatMap({ (key, value) -> String in
return "\(key)=\(value)"
}) as Array).joined(separator: ";")
print(cookieHeader) // key2=value2;key1=value1
Jano's answer using Swift 5.1:
let dic = ["key1": "value1", "key2": "value2"]
let cookieHeader = dic.map { $0.0 + "=" + $0.1 }.joined(separator: ";")
print(cookieHeader) // key2=value2;key1=value1
You can just print a dictionary directly without embedding it into a string:
let dict = ["foo": "bar", "answer": "42"]
println(dict)
// [foo: bar, answer: 42]
Or you can embed it in a string like this:
let dict = ["foo": "bar", "answer": "42"]
println("dict has \(dict.count) items: \(dict)")
// dict has 2 items: [foo: bar, answer: 42]