Convert Model to dictionary (even model have a model in it)

PHOTO EMBED

Tue Aug 22 2023 07:02:05 GMT+0000 (Coordinated Universal Time)

Saved by @hasnat #ios #swift #model #dictionary #dict

extension Encodable {
    func toDictionary() -> [String: Any]? {
        do {
            let encoder = JSONEncoder()
            let data = try encoder.encode(self)
            let dictionary = try JSONSerialization.jsonObject(with: data, options: .allowFragments) as? [String: Any]
            return dictionary
        } catch {
            print("Error converting to dictionary:", error)
            return nil
        }
    }
}
content_copyCOPY