Created
April 6, 2021 08:14
-
-
Save cristhianleonli/2d2c016a71ac0fcfd94923a27125827d 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
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