Toland Hon Toland Hon - 3 months ago 80
Swift Question

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"]


Is there a way in Swift to get it to pretty print dictionaries where each key-value pair occupies a new line?

Answer

You could use dump, for example, if the goal is to inspect the dictionary.

dump is part of Swift's standard library.

Usage:

let dictionary: [String : String] = ["A" : "alfa",
                                     "B" : "bravo",
                                     "C" : "charlie",
                                     "D" : "delta",
                                     "E" : "echo",
                                     "F" : "foxtrot"]

dump(dictionary)

Output:

enter image description here

Comments