Skip to content

Instantly share code, notes, and snippets.

@guidomb
Created July 30, 2018 13:58
Show Gist options
  • Save guidomb/9c4bbcef9bdc7c3e3e8b75c7b9a11c08 to your computer and use it in GitHub Desktop.
Save guidomb/9c4bbcef9bdc7c3e3e8b75c7b9a11c08 to your computer and use it in GitHub Desktop.
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