当前位置: 首页 > article >正文

Swift如何优雅漂亮的打印字典、json

Swift如何优雅漂亮的打印字典、json

Prettier debug output printing Swift Dictionary in Xcode

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

在Swift中,使用print()打印字典的时候,打印出来的样式如下

object = Optional({
customerId = 111;
transactionId = 333;
extraId = 444;
})

When I run po on that same dictionary, it spits out this nonsense dump which is incredibly hard to read.

当使用po 来打印同一个字典的时候,打印出来的另外一种更难阅读的样式如下:

▿ Optional<Any>
▿ some : 3 elements
▿ 0 : 2 elements
  ▿ .0 : transactionId
  - .1 : 333
▿ 1 : 2 elements
  ▿ .0 : customerId
  - .1 : 111
▿ 2 : 2 elements
  ▿ .0 : extraId
  - .1 : 444

Using just p is even worse

如果使用p来打印的话,看着更遭

(Any?) $R8 = some {
  payload_data_0 = 0x0000000170e679c0 {
  Swift._SwiftNativeNSDictionary = {}
  _heapBufferBridged_DoNotUse = 0x0000000170e679d0 {}
  nativeStorage = {
    buffer = 0x00000001703e4300 {
      Swift.ManagedBuffer = {}
    }
    initializedEntries = (values = 0x00000001703e4328, bitCount = 4)
    keys = 0x00000001703e4330
    values = 0x00000001703e4390
    }
  }
  payload_data_1 = 0x0000000000000000
  payload_data_2 = 0x0000000000000000
  instance_type = 0x0000000105ffc3f8
}

What can I do in the console to see my variables in a way that I can actually read them without having to sift through all this nonsense?

PS - In this case I am printing an Optional<Any> object that happens to be a dictionary, but it’s the same with a non-optional Dictionary.

解决方案如下:

第一种方案:

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.

第二种解决方案:

第一种方案只能给一个单行的打印出来

⚠️ 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
}

Share

Improve this answer

Follow

edited Apr 22, 2021 at 0:10

pkamb

33.5k2323 gold badges161161 silver badges191191 bronze badges

answered Sep 15, 2020 at 21:28

2,5492020 silver badges2424 bronze badges

  • entering your permanent echo command in Terminal results in zsh: event not found: ))/and/or bash: !: event not found. Do you know the problem or how to fix?

    – pkamb

    Apr 22, 2021 at 16:40

  • 2

    @pkamb Looks like you’re running into this: serverfault.com/questions/208265/… Probably can be worked around by escaping some characters, but I’m not going to play that game. Instead, you can just copy the command (between the double quotes, or listed above), and add it to the ~/.lldbinit file.

    – agirault

    Apr 27, 2021 at 15:52

  • How can I get a value selected from the dictionary content?

    – SimonKravis

    Mar 28, 2022 at 1:04

原文 :https://stackoverflow.com/questions/42236555/prettier-debug-output-printing-swift-dictionary-in-xcode/63910097#63910097

使用swift代码自定义lldb命令 : https://juejin.cn/post/6977212326424346661


http://www.kler.cn/news/109051.html

相关文章:

  • RabbitMQ学习04
  • conda: error: argument COMMAND: invalid choice: ‘activate‘
  • 阿里云2023年双11活动时间、活动入口、活动内容详细解读
  • 程序化交易(二)level2行情数据源接入
  • LeetCode题:88合并两个有序数组,283移动零,448找到所有数组中消失的数字
  • idea 没加载 provided的包
  • GoLong的学习之路(十二)语法之标准库 flag的使用
  • LeetCode 125 验证回文串 简单
  • stream流—关于Collectors.toMap使用详解
  • Ubuntu服务器中java -jar 后台运行Spring Boot项目
  • 精通Nginx(01)-产品概览
  • 物联网数据采集网关连接设备与云平台的关键桥梁
  • calloc、malloc、realloc函数的区别及用法
  • 【力扣SQL】几个常见SQL题
  • 并发编程
  • uniapp开发小程序—根据生日日期计算年龄 周岁
  • 【自动驾驶】Free space与Ray casting
  • SpringBoot面试题8:运行 Spring Boot 有哪几种方式?Spring Boot 需要独立的容器运行吗?
  • ubuntu 18 更新git版本到 2.80.1
  • 深度学习之轻量级神经网络在TWS蓝牙音频处理器上的部署
  • 求二进制最低位1和最高位1的方法,以及反转二进制,复杂度O(1)
  • Python-easygui
  • 开发库介绍
  • 链游风暴再起?MBOX即将再度起飞
  • O(1) 时间插入、删除和获取随机元素
  • 你会处理 go 中的 nil 吗
  • ChatGPT 驱动软件开发:AI 在软件研发全流程中的革新与实践
  • 38基于matlab的期货预测,利用PSO优化SVM和未优化的SVM进行对比,得到实际输出和期望输出结果。
  • 万字解析设计模式之单例模式
  • 为wget命令设置代理