Skip to content

Instantly share code, notes, and snippets.

@cristhianleonli
Created April 6, 2021 08:14
Show Gist options
  • Save cristhianleonli/2d2c016a71ac0fcfd94923a27125827d to your computer and use it in GitHub Desktop.
Save cristhianleonli/2d2c016a71ac0fcfd94923a27125827d to your computer and use it in GitHub Desktop.
import Foundation
extension Decodable {
static func parse(from item: Any?, strategy: JSONDecoder.KeyDecodingStrategy = .useDefaultKeys) -> Self? {
let decoder = JSONDecoder()
decoder.keyDecodingStrategy = strategy
do {
guard let data = self.data(from: item) else {
return nil
}
return try decoder.decode(Self.self, from: data)
} catch {
print(error.localizedDescription)
}
return nil
}
private static func data(from item: Any?) -> Data? {
switch item {
case let data as Data:
return data
case let string as String:
return string.data(using: .utf8)
case let item?:
return try? JSONSerialization.data(withJSONObject: item, options: [])
default:
return nil
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment