blog
blog copied to clipboard
How to provide default Codable in Swift
Use DefaultValue
to provide defaultValue
in our property wrapper DefaultCodable
public protocol DefaultValue {
associatedtype Value: Codable
static var defaultValue: Value { get }
}
public enum DefaultBy {
public enum True: DefaultValue {
public static let defaultValue = true
}
public enum False: DefaultValue {
public static let defaultValue = false
}
}
@propertyWrapper
public struct DefaultCodable<T: DefaultValue> {
public var wrappedValue: T.Value
public init(wrappedValue: T.Value) {
self.wrappedValue = wrappedValue
}
}
extension DefaultCodable: Equatable where T.Value: Equatable {
public static func == (l: DefaultCodable, r: DefaultCodable) -> Bool {
l.wrappedValue == r.wrappedValue
}
}
extension DefaultCodable: Codable {
public init(from decoder: Decoder) throws {
let container = try decoder.singleValueContainer()
do {
wrappedValue = try container.decode(T.Value.self)
} catch {
wrappedValue = T.defaultValue
}
}
public func encode(to encoder: Encoder) throws {
try wrappedValue.encode(to: encoder)
}
}
Read more
- https://jierong.dev/2021/02/26/providing-default-value-for-decodable-property-by-property-wrapper.html
- https://github.com/marksands/BetterCodable