Created
February 22, 2021 21:50
-
-
Save jordanebelanger/4362b58da3bd00176205eefd1df3128c 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
public struct ResultCodable<CodableType>: Codable where CodableType: Codable { | |
private enum EncodingError: Swift.Error, CustomStringConvertible { | |
case encodedErrorResult(encodingError: Swift.Error) | |
var description: String { | |
switch self { | |
case .encodedErrorResult(let encodingError): | |
return "Cannot encode `Result.failure` which resulted from decoding error: '\(encodingError)'" | |
} | |
} | |
} | |
public let result: Result<CodableType, Swift.Error> | |
public init(value: CodableType) { | |
self.result = .success(value) | |
} | |
public init(from decoder: Decoder) throws { | |
let container = try decoder.singleValueContainer() | |
do { | |
self.result = try .success(container.decode(CodableType.self)) | |
} catch { | |
self.result = .failure(error) | |
} | |
} | |
public func encode(to encoder: Encoder) throws { | |
var container = encoder.singleValueContainer() | |
switch result { | |
case .success(let value): | |
try container.encode(value) | |
case .failure(let error): | |
assertionFailure("Attempting to encode a `Result.failure` should never be done.") | |
throw EncodingError.encodedErrorResult(encodingError: error) | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment