From 6b68141e31377c206d85b92dc48fa219495795a8 Mon Sep 17 00:00:00 2001 From: Dominic Go Date: Fri, 27 Sep 2024 11:43:01 +0800 Subject: [PATCH] =?UTF-8?q?=E2=AD=90=EF=B8=8F=20Impl:=20`Encodable+Helpers?= =?UTF-8?q?`?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- ios/Temp/Encodable+Helpers.swift | 40 ++++++++++++++++++++++++++++++++ 1 file changed, 40 insertions(+) create mode 100644 ios/Temp/Encodable+Helpers.swift diff --git a/ios/Temp/Encodable+Helpers.swift b/ios/Temp/Encodable+Helpers.swift new file mode 100644 index 00000000..3ffa3f7c --- /dev/null +++ b/ios/Temp/Encodable+Helpers.swift @@ -0,0 +1,40 @@ +// +// Encodable+Helpers.swift +// react-native-ios-modal +// +// Created by Dominic Go on 9/27/24. +// + +import Foundation +import DGSwiftUtilities + + +public extension Encodable { + + /// Encode into JSON and return `Data` + func convertToJsonData() throws -> Data { + let encoder = JSONEncoder(); + encoder.outputFormatting = .prettyPrinted; + encoder.dateEncodingStrategy = .iso8601; + + return try encoder.encode(self); + }; + + func convertToJsonDictionary() throws -> [String: Any] { + let jsonData = try self.convertToJsonData(); + + let jsonObject = try JSONSerialization.jsonObject( + with: jsonData, + options: [] + ); + + guard let jsonDict = jsonObject as? [String : Any] else { + throw GenericError( + errorCode: .typeCastFailed, + description: "Unable to convert json object to dictionary" + ); + }; + + return jsonDict; + }; +};