有没有一种方法可以将Swift字典漂亮地打印到控制台上? [英] Is there a way to pretty print Swift dictionaries to the console?
问题描述
NSDictionary *dictionary = @{@"A" : @"alfa",
@"B" : @"bravo",
@"C" : @"charlie",
@"D" : @"delta",
@"E" : @"echo",
@"F" : @"foxtrot"};
NSLog(@"%@", dictionary.description);
在控制台上打印出以下内容:
prints out the following on the console:
{
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)
在控制台上打印出以下内容:
prints out the following on the console:
["B": "bravo", "A": "alfa", "F": "foxtrot", "C": "charlie", "D": "delta", "E": "echo"]
Swift中是否有一种方法可以将其带到漂亮的打印字典中,其中每个键值对都占一行?
Is there a way in Swift to get it to pretty print dictionaries where each key-value pair occupies a new line?
推荐答案
您可以使用 dump (例如,如果目标是检查字典). dump
是Swift标准库的一部分.
You could use dump, for example, if the goal is to inspect the dictionary. dump
is part of Swift's standard library.
用法:
let dictionary: [String : String] = ["A" : "alfa",
"B" : "bravo",
"C" : "charlie",
"D" : "delta",
"E" : "echo",
"F" : "foxtrot"]
dump(dictionary)
输出:
dump
通过反射(镜像)打印对象的内容.
dump
prints the contents of an object via reflection (mirroring).
阵列的详细视图:
let names = ["Joe", "Jane", "Jim", "Joyce"]
dump(names)
打印:
▿4个元素
-[0]:乔
-[1]:简
-[2]:吉姆
-[3]:乔伊斯
▿ 4 elements
- [0]: Joe
- [1]: Jane
- [2]: Jim
- [3]: Joyce
对于字典:
let attributes = ["foo": 10, "bar": 33, "baz": 42]
dump(attributes)
打印:
▿3个键/值对
▿[0] :( 2个元素)
-.0:bar
-.1:33
▿[1] :( 2个元素)
-.0:baz
-.1:42
▿[2] :( 2个元素)
-.0:foo
-.1:10
▿ 3 key/value pairs
▿ [0]: (2 elements)
- .0: bar
- .1: 33
▿ [1]: (2 elements)
- .0: baz
- .1: 42
▿ [2]: (2 elements)
- .0: foo
- .1: 10
dump
被声明为dump(_:name:indent:maxDepth:maxItems:)
.
第一个参数没有标签.
还有其他可用参数,例如name
可以为要检查的对象设置标签:
There's other parameters available, like name
to set a label for the object being inspected:
dump(attributes, name: "mirroring")
打印:
▿镜像:3个键/值对
▿[0] :( 2个元素)
-.0:bar
-.1:33
▿[1] :( 2个元素)
-.0:baz
-.1:42
▿[2] :( 2个元素)
-.0:foo
-.1:10
▿ mirroring: 3 key/value pairs
▿ [0]: (2 elements)
- .0: bar
- .1: 33
▿ [1]: (2 elements)
- .0: baz
- .1: 42
▿ [2]: (2 elements)
- .0: foo
- .1: 10
您还可以选择使用maxItems:
仅打印特定数量的项目,使用maxDepth:
解析到一定深度的对象,并使用indent:
更改打印对象的压痕.
You can also choose to print only a certain number of items with maxItems:
, to parse the object up to a certain depth with maxDepth:
, and to change the indentation of printed objects with indent:
.
这篇关于有没有一种方法可以将Swift字典漂亮地打印到控制台上?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!