Created
February 12, 2020 08:16
-
-
Save tonyarnold/2ed54a0fac1bf93925a257fe748f5fbb to your computer and use it in GitHub Desktop.
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
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) | |
} | |
} |
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
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