Skip to content

Instantly share code, notes, and snippets.

@art-divin
Created March 7, 2019 05:44
Show Gist options
  • Save art-divin/d65c8a33f2ca22b9c6d8631e781a8f37 to your computer and use it in GitHub Desktop.
Save art-divin/d65c8a33f2ca22b9c6d8631e781a8f37 to your computer and use it in GitHub Desktop.
Swift deserialization
infix operator <<<
class Entity : CustomDebugStringConvertible {
static func <<<(_ image: Entity, assignment: (ReferenceWritableKeyPath<Entity, String?>, key: Entity.Keys, source: [String : Any])) {
let keypath = assignment.0
let value = assignment.source[assignment.key.rawValue]
if value != nil {
image[keyPath: keypath] = String(describing: value!)
} else {
image[keyPath: keypath] = nil
}
}
enum Keys : String, CaseIterable {
case keyA = "keyA"
case keyB = "keyB"
case keyC = "keyC"
case keyD = "keyD"
var keyPath: ReferenceWritableKeyPath<Entity, String?> {
switch self {
case .keyA: return \Entity.keyA
case .keyB: return \Entity.keyB
case .keyC: return \Entity.keyC
case .keyD: return \Entity.keyD
}
}
}
private var keyA : String?
private var keyB : String?
private var keyC : String?
private var keyD : String?
init(dictionary: [String : Any]) {
for cs in Keys.allCases {
self <<< (cs.keyPath, key: cs, dictionary)
}
}
var debugDescription: String {
var retVal : String = ""
for cs in Keys.allCases {
retVal.append("\(self[keyPath: cs.keyPath])\n")
}
return retVal
}
}
let entity = Entity(dictionary: [ "keyA" : "1", "keyB" : "2", "keyC" : "3", "keyD" : "4" ])
print(entity)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment