Skip to content

Instantly share code, notes, and snippets.

@kot331107
Created July 10, 2022 22:08
Show Gist options
  • Save kot331107/9089e1430938fdb8470968c60c085a02 to your computer and use it in GitHub Desktop.
Save kot331107/9089e1430938fdb8470968c60c085a02 to your computer and use it in GitHub Desktop.
converts dictionary to JSON
//
// main.swift
// swift challenges
//
// Created by Filipp Mikheev on 11.07.22.
//
import Foundation
extension Dictionary where Key == String, Value == Any {
var stringified: String? {
do {
let data = try JSONSerialization.data(
withJSONObject: self,
options: .fragmentsAllowed
)
guard let result = String(data: data, encoding: .ascii) else {
return nil
}
return result
} catch let err {
print("😱 error with \(#function): \(err.localizedDescription)")
return nil
}
}
}
var dictionary: [String: Any] = ["a1":"123", "a2":"234", "a3": ["a31":"345", "a32":"456"]]
print(dictionary.stringified ?? "")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment