Convert Swift Dictionary to String

2019-03-10 15:49发布

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.

标签: swift ios8
3条回答
走好不送
2楼-- · 2019-03-10 16:23

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
查看更多
我命由我不由天
3楼-- · 2019-03-10 16:24

Just use the description property of CustomStringConvertible as

Example:

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

查看更多
甜甜的少女心
4楼-- · 2019-03-10 16:27

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]
查看更多
登录 后发表回答