본문 바로가기

프로그래밍/iOS,macOS

Codable for Dictionary

extension Encodable {
   func getValue() throws -> [String:Any] {
      let data = try JSONEncoder().encode(self)
      if let dictionary = try JSONSerialization.jsonObject(with: data, options: .allowFragments) as? [String:Any] {
         return dictionary
      }
      throw NSError()
   }
}

extension Decodable {
   func setValue(from: [String:Any] ) throws {
      let data = try JSONSerialization.data(withJSONObject: from, options: .prettyPrinted)
      let decoder = JSONDecoder()
      self = try decoder.decode(Self.self, from: data)
   }
}