Skip to content

Instantly share code, notes, and snippets.

@kylehughes
Last active February 20, 2023 04:35
Show Gist options
  • Save kylehughes/65e9e69006eafd2ccc90209c61ee2585 to your computer and use it in GitHub Desktop.
Save kylehughes/65e9e69006eafd2ccc90209c61ee2585 to your computer and use it in GitHub Desktop.
An example of how to implement Codable support for a type that conforms to LosslessStringConvertible.
// MARK: - Default Decodable Implementation
extension Decodable where Self: LosslessStringConvertible {
// MARK: Public Initialization
public init(from decoder: Decoder) throws {
let container = try decoder.singleValueContainer()
let stringValue = try container.decode(String.self)
guard let value = Self(stringValue) else {
throw DecodingError.dataCorruptedError(
in: container,
debugDescription: "Expected to be able to losslessly convert from String."
)
}
self = value
}
}
// MARK: - Default Encodable Implementation
extension Encodable where Self: LosslessStringConvertible {
// MARK: Public Instance Interface
func encode(to encoder: Encoder) throws {
var container = encoder.singleValueContainer()
try container.encode(description)
}
}
@kylehughes
Copy link
Author

kylehughes commented Feb 19, 2023

This is done as a default implementation for all types that conform to LosslessStringConvertible. Creating such conformances on standard library types is not advised in production. If you want to ship this I would advise scoping the implementation to just your specific type(s), or defining your own LosslessStringConvertible-implementing protocol (e.g. LosslessStringCodable) and scoping the default implementation to implementers of that protocol.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment