Open onmyway133 opened 2 years ago
Use DefaultValue to provide defaultValue in our property wrapper DefaultCodable
DefaultValue
defaultValue
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) } }
Use
DefaultValue
to providedefaultValue
in our property wrapperDefaultCodable
Read more