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

前端 未结 16 990
北海茫月
北海茫月 2020-12-07 09:33
NSDictionary *dictionary = @{@\"A\" : @\"alfa\",
                             @\"B\" : @\"bravo\",
                             @\"C\" : @\"charlie\",
                       


        
16条回答
  •  清歌不尽
    2020-12-07 10:12

    For debug purpose only I would convert the Array or Dictionary to a pretty printed json:

    public extension Collection {
    
        /// Convert self to JSON String.
        /// Returns: the pretty printed JSON string or an empty string if any error occur.
        func json() -> String {
            do {
                let jsonData = try JSONSerialization.data(withJSONObject: self, options: [.prettyPrinted])
                return String(data: jsonData, encoding: .utf8) ?? "{}"
            } catch {
                print("json serialization error: \(error)")
                return "{}"
            }
        }
    }
    

    Then:

    print("\nHTTP request: \(URL)\nParams: \(params.json())\n")
    

    Result on console:

    HTTP request: https://example.com/get-data
    Params: {
      "lon" : 10.8663676,
      "radius" : 111131.8046875,
      "lat" : 23.8063882,
      "index_start" : 0,
      "uid" : 1
    }
    

提交回复
热议问题