将Swift字典转换为字符串

将Swift字典转换为字符串,swift,ios8,Swift,Ios8,为了测试和调试,我尝试将字典的内容设置为字符串。但不知道它将如何实现。可能吗?如果是,如何进行 字典是从web服务获取的,所以我不知道它的键值。我想使用应用程序中的数据 在Objective C%@中,足以在NSString中存储任何内容。您可以直接打印字典,而无需将其嵌入字符串: let dict = ["foo": "bar", "answer": "42"] println(dict) // [foo: bar, answer: 42] 或者可以将其嵌入如下字符串中: let dict

为了测试和调试,我尝试将字典的内容设置为字符串。但不知道它将如何实现。可能吗?如果是,如何进行

字典是从web服务获取的,所以我不知道它的键值。我想使用应用程序中的数据


在Objective C%@中,足以在NSString中存储任何内容。

您可以直接打印字典,而无需将其嵌入字符串:

let dict = ["foo": "bar", "answer": "42"]

println(dict)
// [foo: bar, answer: 42]
或者可以将其嵌入如下字符串中:

let dict = ["foo": "bar", "answer": "42"]

println("dict has \(dict.count) items: \(dict)")
  // dict has 2 items: [foo: bar, answer: 42]

只需使用
CustomStringConvertible
description
属性即可


注:在Swift 3之前(或之前),
CustomStringConvertible
被称为
Printable

字典,用于自定义格式的字符串:

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
使用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

%@在对象上,只调用description方法。所以你可以只做myDict.description来得到一个字符串。这正是我想要的。在我的例子中,不能将println分配给object-String。(Y) 如果dictionary中的值不是string:string,而是string:array,它会工作吗?“(key)=(value)”代表您调用description,因此结果将是例如
key=[“1”、“2”、“3”]
。如果您想要不同的东西,您必须自定义自己。谈到flatMap的用法,从flatMap返回的元素是一个字符串,不管键和值是什么,所以是的,它将与string:array一起工作。@Jano非常感谢+1,工作得很有魅力!!