Skip to content

Instantly share code, notes, and snippets.

@bre7
Created March 2, 2018 22:04
Show Gist options
  • Save bre7/e5e28187603d606b6a4b1873d6055188 to your computer and use it in GitHub Desktop.
Save bre7/e5e28187603d606b6a4b1873d6055188 to your computer and use it in GitHub Desktop.
Swift Dictionary + Encodable extensions
/// Source: https://stackoverflow.com/questions/45209743/how-can-i-use-swift-s-codable-to-encode-into-a-dictionary
extension Encodable {
/// Converts an Encodable entity to it's Dictionary representation (throwable)
func asDictionary() throws -> [String: Any] {
let data = try JSONEncoder().encode(self)
guard let dictionary = try JSONSerialization.jsonObject(with: data, options: .allowFragments) as? [String: Any] else {
throw NSError()
}
return dictionary
}
/// Converts an Encodable entity to it's Dictionary representation, returns nil otherwise
var dictionary: [String: Any]? {
guard let data = try? JSONEncoder().encode(self) else { return nil }
return (try? JSONSerialization.jsonObject(with: data, options: .allowFragments)).flatMap { $0 as? [String: Any] }
}
}
extension Dictionary where Key == String, Value == Any {
/// Pretty prints a Dictionary
func prettyPrint() {
print(self.prettify())
}
/// Source: https://gist.github.com/Edudjr/e8464ccad4f8fa94afdfed84bb7d4882
func prettify() -> String {
var string: String = ""
if let data = try? JSONSerialization.data(withJSONObject: self, options: .prettyPrinted){
if let nstr = NSString(data: data, encoding: String.Encoding.utf8.rawValue){
string = nstr as String
}
}
return string
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment