Skip to content

Instantly share code, notes, and snippets.

@sambhav7890
Created December 5, 2017 10:32
Show Gist options
  • Save sambhav7890/9442e526c49f351d8fb6ae55e7639fbe to your computer and use it in GitHub Desktop.
Save sambhav7890/9442e526c49f351d8fb6ae55e7639fbe to your computer and use it in GitHub Desktop.
Helper Extensions For Codable Protocol
/*
Use with Dictionary data
let object:DecodableType? = DecodableType.create(dictionaryData)
*/
extension Decodable {
static func create(object: Any) -> Self? {
guard let dataDict = object as? [String: Any] else { return nil }
guard let data = try? JSONSerialization.data(withJSONObject: dataDict, options: JSONSerialization.WritingOptions(rawValue: 0)) else { return nil }
let decodedData = try? JSONDecoder().decode(Self.self, from: data)
return decodedData
}
}
/*
Use to handle array conversions which may have some datapoints with missing/invalid data
*/
extension UnkeyedDecodingContainer {
mutating func lossyDecodeArray<T>(_ type: T.Type) -> [T] where T : Decodable {
var decodedResults: [T] = []
while (!self.isAtEnd) {
if let recordDetail = try? self.decode(type) {
decodedResults.append(recordDetail)
} else {
_ = try? self.decode(AnyCodable.self)
}
}
return decodedResults
}
}
/*
Directly use to handle array conversions which may have some datapoints with missing/invalid data
let items: [DecodableType] = container.lossyDecode(DecodableType.self, forKey: SerializationKeys.Name)
*/
extension KeyedDecodingContainer {
func lossyDecode<U>(_ type: U.Type, forKey key: K) -> [U] where U: Decodable {
do {
var listItemContainer = try self.nestedUnkeyedContainer(forKey: key)
let list = listItemContainer.lossyDecodeArray(type)
return list
} catch {
return []
}
}
}
//Needed to handle skipping parts of invalid jsons
struct AnyCodable: Codable {}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment