Last active
February 20, 2023 04:35
-
-
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.
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
// 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) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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 ownLosslessStringConvertible
-implementing protocol (e.g.LosslessStringCodable
) and scoping the default implementation to implementers of that protocol.