Greetings, traveler!
Have you ever tried printing out server response data in the console? I guess you do. Let’s consider an example.
let json = """
{
"id": "22",
"title": "livsycode",
"info": {
"info1": { "status": "ready" },
"info2": { "time": "22:11" },
}
}
"""
let jsonData = json.data(using: .utf8) ?? .init()
To check out the result, we can create an extension for Data
.
extension Data {
var string: String {
String(decoding: self, as: UTF8.self)
}
}
Then, use a breakpoint to print out the result:
po jsonData.string
We will gain this result then:
"{\n \"id\": \"22\",\n \"title\": \"livsycode\",\n \"info\": {\n \"info1\": { \"status\": \"ready\" },\n \"info2\": { \"time\": \"22:11\" },\n }\n}"
It could be more convenient, so we can consider a different approach. In Swift, there are two types of strings: String
and NSString
. String
is the newer type, and it is often preferred over NSString
, which is older and used in Objective-C as well. However, you can use NSString
for pretty printing. It will provide a nicer debug description since it automatically removes some characters like backslashes. So, to achieve a better string visualization in the console, we should use NSString
instead of String
. To create a pretty printed string, we must follow several steps:
- Create
jsonObject
. - Create data with the
.prettyPrinted
option. - Create
NSString
.
Now, we can put it all together inside an extension.
extension Data {
var jsonString: NSString? {
guard
let jsonObject = try? JSONSerialization.jsonObject(
with: self,
options: []
),
let data = try? JSONSerialization.data(
withJSONObject: jsonObject,
options: [.prettyPrinted]
),
let json = NSString(
data: data,
encoding: String.Encoding.utf8.rawValue
)
else { return nil }
return json
}
}
Let’s check out the result.
po jsonData.jsonString
▿ Optional<NSString>
- some : {
"id" : "22",
"title" : "livsycode",
"info" : {
"info1" : {
"status" : "ready"
},
"info2" : {
"time" : "22:11"
}
}
}
Nice!
Conclusion
Debugging plays a vital role in programming, and it’s always satisfying when it becomes a bit easier.
If you enjoyed this article, please feel free to follow me on my social media: