Skip to content

Instantly share code, notes, and snippets.

@tonyarnold
Created February 12, 2020 08:16
Show Gist options
  • Save tonyarnold/2ed54a0fac1bf93925a257fe748f5fbb to your computer and use it in GitHub Desktop.
Save tonyarnold/2ed54a0fac1bf93925a257fe748f5fbb to your computer and use it in GitHub Desktop.
import Foundation
@propertyWrapper
struct StringCoded<WrappedValue: LosslessStringConvertible>: Codable {
var wrappedValue: WrappedValue
init(wrappedValue: WrappedValue) {
self.wrappedValue = wrappedValue
}
init(from decoder: Decoder) throws {
let container = try decoder.singleValueContainer()
let stringValue = try container.decode(String.self)
guard let value = WrappedValue(stringValue) else {
throw DecodingError.dataCorruptedError(
in: container,
debugDescription: "Unable to initialize an \(WrappedValue.self) using decoded value '\(stringValue)'."
)
}
self.init(wrappedValue: value)
}
func encode(to encoder: Encoder) throws {
var container = encoder.singleValueContainer()
try container.encode(wrappedValue.description)
}
}
import Foundation
@propertyWrapper
struct StringCodedOptional<Wrapped: LosslessStringConvertible>: Codable {
var wrappedValue: Wrapped?
init(wrappedValue: Wrapped? = nil) {
self.wrappedValue = wrappedValue
}
init(from decoder: Decoder) throws {
let container = try decoder.singleValueContainer()
let stringValue = try container.decode(String.self)
let value = Wrapped(stringValue)a
self.init(wrappedValue: value)
}
func encode(to encoder: Encoder) throws {
var container = encoder.singleValueContainer()
if let wrappedValue = wrappedValue {
try container.encode(String(describing: wrappedValue))
} else {
try container.encode("")
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment