khunshan
khunshan

Reputation: 2852

Convert Swift Dictionary to String

For testing and debugging I am trying to put the content of Dictionary to a String. But have no clue hows it going to achieve. Is it possible? If yes, how.

Dictionary is fetched from web service so I have no idea the key values it have. I want to use the data in app.

In Objective C %@ was enough to store anything in NSString.

Upvotes: 65

Views: 88741

Answers (5)

Frederic Adda
Frederic Adda

Reputation: 6092

I'm not sure description is a reliable way to convert a dictionary into a JSON String. There is always the possibility that Apple would change it in the future.

We should use JSONSerialization:

let jsonData = try? JSONSerialization.data(withJSONObject: dict, options: [])
let jsonString = String(data: jsonData!, encoding: .utf8)!

Upvotes: 0

Vicente Garcia
Vicente Garcia

Reputation: 6360

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

Upvotes: 14

GoZoner
GoZoner

Reputation: 70135

Just use the description property of CustomStringConvertible as

Example:

Note: Prior to Swift 3 (or perhaps before), CustomStringConvertible was known as Printable.

Upvotes: 132

Jano
Jano

Reputation: 63667

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

Upvotes: 41

Abhi Beckert
Abhi Beckert

Reputation: 33329

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]

Upvotes: 1

Related Questions