-
-
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
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 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