Skip to content

Instantly share code, notes, and snippets.

@daoseng33
Created July 11, 2018 13:17
Show Gist options
  • Save daoseng33/1ed4ab6cbdd2c84d4ea032d5db4db4af to your computer and use it in GitHub Desktop.
Save daoseng33/1ed4ab6cbdd2c84d4ea032d5db4db4af to your computer and use it in GitHub Desktop.
import Foundation
protocol Convertable: Codable {
}
// Convert struct to dictionary
extension Convertable {
func convertToDict() -> Dictionary<String, Any>? {
var dict: Dictionary<String, Any>? = nil
do {
let encoder = JSONEncoder()
let data = try encoder.encode(self)
dict = try JSONSerialization.jsonObject(with: data, options: .allowFragments) as? Dictionary<String, Any>
} catch {
print(error)
}
return dict
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment