Skip to content

Instantly share code, notes, and snippets.

@jimmythai
Created June 24, 2019 11:04
Show Gist options
  • Select an option

  • Save jimmythai/d7ccd2d359586c9ae4a92992ae342a53 to your computer and use it in GitHub Desktop.

Select an option

Save jimmythai/d7ccd2d359586c9ae4a92992ae342a53 to your computer and use it in GitHub Desktop.
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