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

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


        
相关标签:
16条回答
  • 2020-12-07 10:00

    The methodology of converting the Swift Dictionary to json and back is the neatest. I use Facebook's chisel which has a pjson command to print a Swift dictionary. Eg:

    (lldb) pjson dict as NSDictionary
    

    This should pretty-print the dictionary. This is a much cleaner way to do what has already been suggested. P.S. For now, you'll have to cast dict as NSDictionary because Objective-C runtime doesn't understand Swift dictionaries. I have already raised a PR on chisel to get rid of that restriction.

    UPDATE: My PR got accepted. Now you can use psjson command instead of pjson mentioned above.

    0 讨论(0)
  • When debugging, output the struct that conform Codable Protocol to the console
    use json format.

    extension Encodable {
        var jsonData: Data? {
            let encoder = JSONEncoder()
            encoder.outputFormatting = .prettyPrinted
            return try? encoder.encode(self)
        }
    }
    
    extension Encodable where Self: CustomDebugStringConvertible {
        var debugDescription: String {
             if let data = self.jsonData,
                 let string = String(data: data, encoding: .utf8) {
                 return string
             }
             return "can not convert to json string"
         }
    }
    

    strcut conform CustomDebugStringConvertible

    struct Test: Codable, CustomDebugStringConvertible {
        let a: String
        let b: Int
    }
    
    let t = Test(a: "test string", b: 30)
    

    debug print struct

    (lldb) p print(t)
    {
      "a" : "test string",
      "b" : 30
    }
    
    0 讨论(0)
  • 2020-12-07 10:06

    po solution

    For those of you want to see Dictionary as JSON with out escape sequence in console, here is a simple way to do that

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

    Update

    Check this answer too Answer

    0 讨论(0)
  • 2020-12-07 10:09

    Just another way using Functional Programming

    dictionary.forEach { print("\($0): \($1)") }
    

    Output

    B: bravo
    A: alfa
    F: foxtrot
    C: charlie
    D: delta
    E: echo
    
    0 讨论(0)
  • 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
    }
    
    0 讨论(0)
  • 2020-12-07 10:13

    You can just use a for loop and print each iteration

    for (key,value) in dictionary { 
        print("\(key) = \(value)")
    }
    

    Application in extension:

    extension Dictionary where Key: CustomDebugStringConvertible, Value:CustomDebugStringConvertible {
    
        var prettyprint : String {
            for (key,value) in self {
                print("\(key) = \(value)")
            }
    
            return self.description
        }
    }
    

    Alternate application:

    extension Dictionary where Key: CustomDebugStringConvertible, Value:CustomDebugStringConvertible {
    
        func prettyPrint(){
            for (key,value) in self {
                print("\(key) = \(value)")
            }
        }
    }
    

    Usage:

    dictionary.prettyprint //var prettyprint
    dictionary.prettyPrint //func prettyPrint
    

    Output (Tested in Xcode 8 beta 2 Playground):

    A = alfa
    B = bravo
    C = charlie
    D = delta
    E = echo
    F = foxtrot
    
    0 讨论(0)
提交回复
热议问题