Created
February 9, 2019 15:46
-
-
Save pkuecuekyan/7ba4a6bbd617b60c934a9238924f3941 to your computer and use it in GitHub Desktop.
Parser — a readable and generic μ snippet for JSON/Codable parsing
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
// | |
// Parser | |
// | |
// | |
struct Parser<T: Decodable> { | |
static func parse(_ data: Data) -> T? { | |
var parsedPayload: T? | |
do { | |
parsedPayload = try JSONDecoder().decode(T.self, from: data) | |
} catch { | |
debugPrint("parsing failed with error \"\(error)\" while expected to return type \"\(type(of: T.self))\"") | |
} | |
return parsedPayload | |
} | |
} | |
struct Dog: Codable { | |
enum CodingKeys: String, CodingKey { | |
case image = "message" | |
} | |
public let image: String | |
} | |
URLSession.shared.dataTask(with: URL(string: "https://dog.ceo/api/breeds/image/random")!) { (data, _, _) in | |
guard let data = data else { return } | |
if let parsed = Parser<Dog>.parse(data) { | |
print(parsed) | |
} | |
}.resume() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment