Created
July 30, 2018 13:58
-
-
Save guidomb/9c4bbcef9bdc7c3e3e8b75c7b9a11c08 to your computer and use it in GitHub Desktop.
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
public protocol JSONRepresentable: Encodable { | |
func asJsonData() throws -> Data | |
func asJson() throws -> [String : Any]? | |
} | |
extension JSONRepresentable { | |
public func asJsonData() throws -> Data { | |
return try JSONEncoder().encode(self) | |
} | |
public func asJson() throws -> [String : Any]? { | |
return (try JSONSerialization.jsonObject(with: asJsonData(), options: .allowFragments)) as? [String : Any] | |
} | |
} | |
// | |
// Somewhere inside a serialization function | |
// | |
default: | |
let innerSkipFields = filterSkipFields(skipFields, property: label) | |
if let jsonRepresentable = value as? JSONRepresentable, // This forces static dispatch | |
let maybeJson = try? jsonRepresentable.asJson(), | |
let json = maybeJson, | |
let mapValue = serializeFields(object: json, skipFields: innerSkipFields) { | |
fields[label] = .mapValue(MapValue(fields: mapValue)) | |
} else { | |
print("WARN - Unable to serialize property '\(label)' with value '\(value)' into FirestoreDocument.Value") | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment