Created
June 24, 2019 11:04
-
-
Save jimmythai/d7ccd2d359586c9ae4a92992ae342a53 to your computer and use it in GitHub Desktop.
This file contains hidden or 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 StructToDictionary: Encodable { | |
| var dictionary: [String: Any]? { get } | |
| } | |
| extension StructToDictionary { | |
| var dictionary: [String: Any]? { | |
| let encoder = JSONEncoder() | |
| encoder.keyEncodingStrategy = .convertToSnakeCase | |
| guard let data = try? encoder.encode(self) else { | |
| return nil | |
| } | |
| let jsonObject = try? JSONSerialization.jsonObject(with: data, options: .allowFragments) | |
| let dictionary = jsonObject.flatMap { $0 as? [String: Any] } | |
| return dictionary | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment