Skip to content

Instantly share code, notes, and snippets.

@ts95
Created January 7, 2023 18:41
Show Gist options
  • Save ts95/bc64b6f77e6cdfc0eb5f2e3fa5f0f33e to your computer and use it in GitHub Desktop.
Save ts95/bc64b6f77e6cdfc0eb5f2e3fa5f0f33e to your computer and use it in GitHub Desktop.
Makes the Result type in Swift conform to Codable
import Foundation
extension Result: Codable where Success: Codable, Failure: Codable {
public init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
switch try container.decode(ResultType.self, forKey: .type) {
case .success:
self = .success(try container.decode(Success.self, forKey: .value))
case .failure:
self = .failure(try container.decode(Failure.self, forKey: .value))
}
}
public func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: CodingKeys.self)
switch self {
case .success(let value):
try container.encode(ResultType.success, forKey: .type)
try container.encode(value, forKey: .value)
case .failure(let error):
try container.encode(ResultType.failure, forKey: .type)
try container.encode(error, forKey: .value)
}
}
enum CodingKeys: CodingKey {
case type
case value
}
enum ResultType: Codable {
case success
case failure
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment