Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to pretty print Swift dictionaries to the console?

Tags:

xcode

ios

swift

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?

like image 942
Toland Hon Avatar asked Aug 04 '16 17:08

Toland Hon


People also ask

How do I print a dictionary in Swift?

To print all the keys of a dictionary, we can iterate over the keys returned by Dictionary. keys or iterate through each (key, value) pair of the dictionary and then access the key alone.

Is dictionary mutable in Swift?

If you assign a created dictionary to a variable, then it is always mutable which means you can change it by adding, removing, or changing its items. But if you assign a dictionary to a constant, then that dictionary is immutable, and its size and contents cannot be changed.

Why is dictionary unordered in Swift?

Sets are unordered collections of unique values. Dictionaries are unordered collections of key-value associations. Arrays, sets, and dictionaries in Swift are always clear about the types of values and keys that they can store. This means that you can't insert a value of the wrong type into a collection by mistake.


2 Answers

po solution

For those of you want to see Dictionary as JSON with out escape sequence in console, here is a simple way to do that

(lldb)p print(String(data: try! JSONSerialization.data(withJSONObject: object, options: .prettyPrinted), encoding: .utf8 )!)

Update

Check this answer too Answer

like image 193
Irshad Mohamed Avatar answered Nov 15 '22 22:11

Irshad Mohamed


Casting a dictionary to 'AnyObject' was the simplest solution for me:

let dictionary = ["a":"b",                   "c":"d",                   "e":"f"] print("This is the console output: \(dictionary as AnyObject)") 

this is the console output

This is easier to read for me than the dump option, but note it won't give you the total number of key-values.

like image 21
Jalakoo Avatar answered Nov 16 '22 00:11

Jalakoo