Skip to content

Instantly share code, notes, and snippets.

@yannisalexiou
Created December 19, 2023 14:26
Show Gist options
  • Save yannisalexiou/ffcb7bf4226e407b8788882e4cc430e9 to your computer and use it in GitHub Desktop.
Save yannisalexiou/ffcb7bf4226e407b8788882e4cc430e9 to your computer and use it in GitHub Desktop.
Simple JSON decoding using protocol and default implementation. With this you can separate the decodable logic from repository and api client
public enum DecodeError: Swift.Error {
case connectivity
case invalidData
}
protocol JSONDecodable {
static func jsonDecode<D: Decodable>(
_ data: Data,
from response: HTTPURLResponse
) throws -> D
}
extension JSONDecodable {
static func jsonDecode<D: Decodable>(
_ data: Data,
from response: HTTPURLResponse
) throws -> D {
guard response.isOK,
let root = try? JSONDecoder().decode(D.self, from: data)
else {
throw DecodeError.invalidData
}
return root
}
}
protocol JSONMapper: JSONDecodable {
typealias GetResult<T> = Swift.Result<T, Error>
static func map<T: Decodable>(
_ data: Data,
from response: HTTPURLResponse
) -> GetResult<T>
}
extension JSONMapper {
static func map<T: Decodable>(
_ data: Data,
from response: HTTPURLResponse
) -> GetResult<T> {
do {
let items: T = try Self.jsonDecode(data, from: response)
return .success(items)
} catch {
return .failure(error)
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment