Skip to content

Instantly share code, notes, and snippets.

@JanGorman
Created May 12, 2020 08:29
Show Gist options
  • Save JanGorman/b4c150182aa2292c98c965dd2c07d87b to your computer and use it in GitHub Desktop.
Save JanGorman/b4c150182aa2292c98c965dd2c07d87b to your computer and use it in GitHub Desktop.
JSON Swift String Interpolation
extension String.StringInterpolation {
mutating func appendInterpolation(json JSONData: Data) {
guard let JSONObject = try? JSONSerialization.jsonObject(with: JSONData, options: []),
let jsonData = try? JSONSerialization.data(withJSONObject: JSONObject, options: .prettyPrinted) else {
appendInterpolation("Invalid JSON data")
return
}
appendInterpolation("\n\(String(decoding: jsonData, as: UTF8.self))")
}
}
// Use
let jsonData = """
{
"name": "Wassily Kandinsky"
}
""".data(using: .utf8)!
print("The provided JSON is \(json: jsonData)")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment