Swift:使用po在控制台格式化打印Dictionary、Array等对象

2022年4月11日 2125点热度 0人点赞 0条评论

Swift:使用po在控制台格式化打印Dictionary、Array等对象

在Objective- C中进行控制台po相应对象时,可以直接格式化输出回显到控制台中,但在Swift中直接po对象,输出的格式都有,但对应实际开发来说其实并不友好,所以我们就需要能更直观的格式打印

示例数据:

{"stationIds":907,"deviationSource":2,"clientIds":"3,1","remark":"She","projectIds":"56,55","deviationType":"1","productLineIds":"1084","imgList":[{"id":29733},{"id":29734}],"securityFeature":"1"}

Swift默认情况下po输出:

(lldb) po dictionary

▿ 9 elements
  ▿ 0 : 2 elements
    - key : "stationIds"
    - value : 907
  ▿ 1 : 2 elements
    - key : "deviationSource"
    - value : 2
  ▿ 2 : 2 elements
    - key : "clientIds"
    - value : "3,1"
  ▿ 3 : 2 elements
    - key : "remark"
    - value : "She"
  ▿ 4 : 2 elements
    - key : "projectIds"
    - value : "56,55"
  ▿ 5 : 2 elements
    - key : "deviationType"
    - value : "1"
  ▿ 6 : 2 elements
    - key : "productLineIds"
    - value : "1084"
  ▿ 7 : 2 elements
    - key : "imgList"
    ▿ value : 2 elements
      ▿ 0 : 1 element
        ▿ 0 : 2 elements
          - key : "id"
          - value : 29733
      ▿ 1 : 1 element
        ▿ 0 : 2 elements
          - key : "id"
          - value : 29734
  ▿ 8 : 2 elements
    - key : "securityFeature"
    - value : "1"

 

而我们更需要直观展示的格式:

{
  "stationIds" : 907,
  "deviationSource" : 2,
  "clientIds" : "3,1",
  "remark" : "She",
  "projectIds" : "56,55",
  "deviationType" : "1",
  "productLineIds" : "1084",
  "imgList" : [
    {
      "id" : 29733
    },
    {
      "id" : 29734
    },
  ],
  "securityFeature" : "1"
}

 

更加直观的显示1

将Dictionary或者Array等转换为AnyObject 进行显示,这个是最简单的

(lldb) po print(dictionary as AnyObject)

输出:
{
    clientIds = "3,1";
    deviationSource = 2;
    deviationType = 1;
    imgList =     (
                {
            id = 29733;
        },
                {
            id = 29734;
        }
    );
    productLineIds = 1084;
    projectIds = "56,55";
    remark = She;
    securityFeature = 1;
    stationIds = 907;
}

 

 

更加直观的显示2

将Dictionary或者Array等进行JSON序列化处置,以String形式展示

 

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

输出:
{
  "stationIds" : 907,
  "deviationSource" : 2,
  "clientIds" : "3,1",
  "remark" : "She",
  "projectIds" : "56,55",
  "deviationType" : "1",
  "productLineIds" : "1084",
  "imgList" : [
    {
      "id" : 29733
    },
    {
      "id" : 29734
    }
  ],
  "securityFeature" : "1"
}

 

 

帮助教程

提供最新的帮助教程,方便使用。

文章评论