Skip to content

Instantly share code, notes, and snippets.

@alekseylichtman
Last active July 25, 2024 06:16
Show Gist options
  • Save alekseylichtman/9df268d899137d0270c0e2476e6d2336 to your computer and use it in GitHub Desktop.
Save alekseylichtman/9df268d899137d0270c0e2476e6d2336 to your computer and use it in GitHub Desktop.
Swift. Convert any object to dictionary
protocol DictionaryConvertible: Codable {
func convertToDictionary() -> [String: Any]
}
extension DictionaryConvertible {
func convertToDictionary() -> [String: Any] {
let jsonEncoder = JSONEncoder()
let jsonData = try! jsonEncoder.encode(self)
do {
return try (JSONSerialization.jsonObject(with: jsonData, options: []) as? [String: Any])!
} catch {
print(error.localizedDescription)
return [:]
}
}
}
@alekseylichtman
Copy link
Author

alekseylichtman commented Apr 22, 2021

Then you only need to inherit your structure from DictionaryConvertible protocol and call method convertToDictionary() on your object.

In return you should get [String: Any] dictionary.

@kuttz
Copy link

kuttz commented Jul 25, 2024

Better to directly extend the Encodable protocol, so that any thing conform to Encodable and the Codable protocol able to get access to that method. No need to add a new protocol.

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment