Created
April 3, 2018 19:37
-
-
Save NeilsUltimateLab/1306efc970715ab7ab79dac2c7e31f7f to your computer and use it in GitHub Desktop.
Decoding Result<A, E> types in swift
This file contains hidden or 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
//: Playground - noun: a place where people can play | |
import UIKit | |
let errorJsonData = """ | |
{ | |
"message": "The message", | |
"reference_url": "https://www.api.refer.co" | |
} | |
""".data(using: .utf8)! | |
let responseJSONData = """ | |
{ | |
"value" : { | |
"name": "DrStrangers", | |
"surname": "We dont have surnames", | |
"id": 2 | |
} | |
} | |
""".data(using: .utf8)! | |
struct Object: Decodable { | |
var name: String | |
var surname: String | |
var id: Int | |
} | |
struct ResponseError: Decodable, Error { | |
var message: String | |
var reference_url: String | |
} | |
enum Result<A> { | |
case value(A) | |
case error(Error) | |
enum CodingKeys: String, CodingKey { | |
case value | |
case error | |
} | |
} | |
extension Result: Decodable where A: Decodable { | |
init(from decoder: Decoder) throws { | |
let container = try decoder.container(keyedBy: CodingKeys.self) | |
if let value = try container.decodeIfPresent(A.self, forKey: .value) { | |
self = .value(value) | |
} else { | |
let errorContainer = try decoder.singleValueContainer() | |
let error = try errorContainer.decode(ResponseError.self) | |
self = .error(error) | |
} | |
} | |
} | |
do { | |
let obj = try JSONDecoder().decode(Result<Object>.self, from: errorJsonData) | |
dump(obj) | |
} catch { | |
print(error) | |
} | |
// PRINTS | |
__lldb_expr_26.Result<__lldb_expr_26.Object>.error | |
▿ error: __lldb_expr_26.ResponseError | |
- message: "The message" | |
- reference_url: "https://www.api.refer.co" | |
do { | |
let obj = try JSONDecoder().decode(Result<Object>.self, from: responseJSONData) | |
dump(obj) | |
} catch { | |
print(error) | |
} | |
// PRINTS | |
__lldb_expr_29.Result<__lldb_expr_29.Object>.value | |
▿ value: __lldb_expr_29.Object | |
- name: "DrStrangers" | |
- surname: "We dont have surnames" | |
- id: 2 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment