Prettier debug output printing Swift Dictionary in Xcode

后端 未结 2 508
隐瞒了意图╮
隐瞒了意图╮ 2021-02-14 22:29

When I use print() on a dictionary in Swift, it comes out nice and pretty in the console, with a key and a value.

object = Optional({
customerId = 1         


        
相关标签:
2条回答
  • 2021-02-14 22:59
    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.

    0 讨论(0)
  • 2021-02-14 23:01

    ⚠️ 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
    }
    
    0 讨论(0)
提交回复
热议问题