Created
July 10, 2022 22:08
-
-
Save kot331107/9089e1430938fdb8470968c60c085a02 to your computer and use it in GitHub Desktop.
converts dictionary to JSON
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// | |
// 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