In Swift, dictionaries will be printed on the same line, which is not beautiful and difficult to read, so I checked online, there are various solutions, such as using dump() function to convert Dictionary into AnyObject (as AnyObjcet), but the effect is not very good. Then I saw an elegant solution in an old project and shared it

The solution

Suppose you have the following dictionary that needs to be printed:

let dic = [
    "name" : "Tony",
    "age" : 18,
    "showType" : true,
    "phone" : "18888888888",
    "enableRealname" : 1,
    "playTimeLimit" : 1
] as [String : Any]
Copy the code

With JSONSerialization we can gracefully print the dictionary to the console:

let data = try! JSONSerialization.data(withJSONObject: dic, options: .prettyPrinted)
let str = String(data: data, encoding: .utf8)!
print(str)
Copy the code

Print result:

The line is wrapped and the value type (String, int, bool) is retained.

encapsulation

It’s too much trouble to write it every time you print it, so we can simply encapsulate it:

extension Dictionary {
    
    func jsonString() -> String {
        if let data = try? JSONSerialization.data(withJSONObject: self, options: .prettyPrinted),
           let jsonStr = String(data: data, encoding: .utf8) {
            return jsonStr
        } else {
            return ""
        }
    }
}
Copy the code

It can then be called directly like this:

print(dic.jsonString())
Copy the code