Last active
July 25, 2024 06:16
-
-
Save alekseylichtman/9df268d899137d0270c0e2476e6d2336 to your computer and use it in GitHub Desktop.
Swift. Convert any object to dictionary
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 [:] | |
} | |
} | |
} |
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
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.