Prettier debug output printing Swift Dictionary in Xcode

⚠️ The (previously) accepted answer only provided the dictionary as a non-formatted single line string like so:

Optional(["transactionId": 333, "customerId": 111, "extraId": 444])

➡️ As soon as you get more keys and embedded objects/dictionaries it becomes difficult to read.


PrettyPrint JSON solution

  • To get a nice json formatting (indentations, newlines, etc) you can define an alias (I named mine pjson) by running this command in your lldb terminal (source):
command regex pjson 's/(.+)/expr print(NSString(string: String(data: try! JSONSerialization.data(withJSONObject: %1, options: .prettyPrinted), encoding: .utf8)!))/'
  • You probably don't want to re-define the alias everytime you open Xcode, so run the following command to append the alias definition to ~/.lldbinit:
echo "command regex pjson 's/(.+)/expr print(NSString(string: String(data: try! JSONSerialization.data(withJSONObject: %1, options: .prettyPrinted), encoding: .utf8)!))/'" >> ~/.lldbinit
  • This will create the pjson alias which you can use in your lldb terminal in Xcode:
pjson object

Comparing the outputs for the following Swift object:

let object: Any? = [
    "customerId": 111,
    "transactionId": 333,
    "extraId": 444,
    "embeddedDict": [
        "foo": true
    ]
]

❌ Output of po print(data)

Optional(["transactionId": 333, "embeddedDict": ["foo": true], "customerId": 111, "extraId": 444])

✅ Output of pjson

{
  "transactionId" : 333,
  "embeddedDict" : {
    "foo" : true
  },
  "customerId" : 111,
  "extraId" : 444
}

New answer (2021):

The fastest way to get readable output is to use:

po print(data)

Say, you have variable data like below:

let data: [String: Any] = ["value1": 64, "value2": true, "value3": "some"]

When you do po print(data), you will get following output:

(lldb) po print(data)
["value1": 64, "value2": true, "value3": "some"]
0 elements

If you're not in a rush you can improve debug printing format following steps from answer in below.

OLD answer (2017):

expression debugPrint(object)

just put the line above in your debugger and hit enter. It will print out contents of our object in more human readable format.

also you can use another one command - po print(data), which is easier to remember.