Skip to content

Instantly share code, notes, and snippets.

@jordanebelanger
Created February 22, 2021 21:50
Show Gist options
  • Save jordanebelanger/4362b58da3bd00176205eefd1df3128c to your computer and use it in GitHub Desktop.
Save jordanebelanger/4362b58da3bd00176205eefd1df3128c to your computer and use it in GitHub Desktop.
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