Codable+Sweeter.swift 813 B

123456789101112131415161718192021222324
  1. //
  2. // Codable+Sweeter.swift
  3. //
  4. // Created by Yonat Sharon on 2019-02-08.
  5. //
  6. import Foundation
  7. public extension Decodable {
  8. /// Sweeter: Create object from a dictionary
  9. init?(dictionary: [String: Any]) {
  10. guard let data = try? JSONSerialization.data(withJSONObject: dictionary, options: .prettyPrinted) else { return nil }
  11. guard let decodedSelf = try? JSONDecoder().decode(Self.self, from: data) else { return nil }
  12. self = decodedSelf
  13. }
  14. }
  15. public extension Encodable {
  16. /// Sweeter: Export object to a dictionary representation
  17. var dictionary: [String: Any]? {
  18. guard let data = try? JSONEncoder().encode(self) else { return nil }
  19. return (try? JSONSerialization.jsonObject(with: data, options: .allowFragments)).flatMap { $0 as? [String: Any] }
  20. }
  21. }