NSDictionary *dictionary = @{@"A" : @"alfa",
@"B" : @"bravo",
@"C" : @"charlie",
@"D" : @"delta",
@"E" : @"echo",
@"F" : @"foxtrot"};
NSLog(@"%@", dictionary.description);
在控制台上打印以下内容:
{
A = alfa;
B = bravo;
C = charlie;
D = delta;
E = echo;
F = foxtrot;
}
let dictionary: [String : String] = ["A" : "alfa",
"B" : "bravo",
"C" : "charlie",
"D" : "delta",
"E" : "echo",
"F" : "foxtrot"];
print(dictionary)
在控制台上打印以下内容:
["B": "bravo", "A": "alfa", "F": "foxtrot", "C": "charlie", "D": "delta", "E": "echo"]
斯威夫特有没有一种方法可以让它成为漂亮的印刷词典,每个键值对占据一条新的线?
发布于 2016-08-04 10:47:04
例如,如果目标是检查字典,可以使用转储。dump
是Swift标准库的一部分。
用法:
let dictionary: [String : String] = ["A" : "alfa",
"B" : "bravo",
"C" : "charlie",
"D" : "delta",
"E" : "echo",
"F" : "foxtrot"]
dump(dictionary)
输出:
dump
通过反射(镜像)打印对象的内容。
数组的详细视图:
let names = ["Joe", "Jane", "Jim", "Joyce"]
dump(names)
指纹:
▿4元素 -乔 - 1:简 - 2: Jim - 3:乔伊斯
一本字典:
let attributes = ["foo": 10, "bar": 33, "baz": 42]
dump(attributes)
指纹:
▿3键/值对 ▿:(2元素) - .0: bar - .1: 33 ▿1:(2个元素) - .0: baz - .1: 42 ▿2:(2个元素) - .0: foo - .1: 10
dump
被声明为dump(_:name:indent:maxDepth:maxItems:)
。
第一个参数没有标签。
还有其他可用的参数,如name
,用于为被检查的对象设置标签:
dump(attributes, name: "mirroring")
指纹:
▿镜像:3个键/值对 ▿:(2元素) - .0: bar - .1: 33 ▿1:(2个元素) - .0: baz - .1: 42 ▿2:(2个元素) - .0: foo - .1: 10
您还可以选择使用maxItems:
只打印一定数量的项,用maxDepth:
解析对象到一定深度,并使用indent:
更改打印对象的缩进。
发布于 2017-10-12 10:39:46
po
解决方案
对于那些希望在console中将字典看作JSON而没有转义序列的人,下面是一种简单的方法:
(lldb) p print(String(data: try! JSONSerialization.data(withJSONObject: object, options: .prettyPrinted), encoding: .utf8)!)
更新
也看看这个答案吧。
发布于 2017-06-14 08:23:27
将字典转换为“AnyObject”对我来说是最简单的解决方案:
let dictionary = ["a":"b",
"c":"d",
"e":"f"]
print("This is the console output: \(dictionary as AnyObject)")
对于我来说,这比转储选项更容易阅读,但请注意,它不会给出键值的总数。
https://stackoverflow.com/questions/38773979
复制相似问题