Created
March 2, 2018 22:04
-
-
Save bre7/e5e28187603d606b6a4b1873d6055188 to your computer and use it in GitHub Desktop.
Swift Dictionary + Encodable extensions
This file contains hidden or 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
/// 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