Skip to content

Instantly share code, notes, and snippets.

@aranasaurus
Forked from IanKeen/DictionaryConvertable.swift
Created September 25, 2015 15:57
Show Gist options
  • Save aranasaurus/42b26f011a8f912d2d01 to your computer and use it in GitHub Desktop.
Save aranasaurus/42b26f011a8f912d2d01 to your computer and use it in GitHub Desktop.
_Very_ basic protocol to handle conversions between Model objects and Dictionaries. Model -> Dictionary has a default implementation provided for simple 1:1 non-nested Models - Will likely adapt this into a lib at some point
protocol DictionaryConvertable {
static func fromDictionary(dictionary: [String: Any]) throws -> Self
func toDictionary() -> [String: Any]
}
extension DictionaryConvertable {
func toDictionary() -> [String: Any] {
let mirror = Mirror(reflecting: self)
return mirror.children.reduce([:]) { result, child in
guard let key = child.label else { return result }
return result + [key: child.value]
}
}
}
func + <K>(left: [K: Any], right: [K: Any]) -> [K: Any] {
var result = [K: Any]()
[left, right].forEach { dict in
dict.forEach { result[$0.0] = $0.1 }
}
return result
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment