import Foundation public protocol DecodableDefaultSource { associatedtype Value: Decodable static var defaultValue: Value { get } } public enum DecodableDefault {} public extension DecodableDefault { @propertyWrapper struct Wrapper { public typealias Value = Source.Value public var wrappedValue = Source.defaultValue public init(wrappedValue: Value = Source.defaultValue) { self.wrappedValue = wrappedValue } } } extension DecodableDefault.Wrapper: Decodable { public init(from decoder: Decoder) throws { let container = try decoder.singleValueContainer() wrappedValue = try container.decode(Value.self) } } public extension KeyedDecodingContainer { func decode(_ type: DecodableDefault.Wrapper.Type, forKey key: Key) throws -> DecodableDefault.Wrapper { try decodeIfPresent(type, forKey: key) ?? .init() } } public protocol ProvidesEmptyPlaceholder: Codable { static var empty: Self { get } } public extension DecodableDefault { typealias Source = DecodableDefaultSource typealias List = Decodable & ExpressibleByArrayLiteral typealias Map = Decodable & ExpressibleByDictionaryLiteral typealias Enum = Decodable & CaseIterable enum Sources { public enum Zero: Source { public static var defaultValue: Int { 0 } } public enum True: Source { public static var defaultValue: Bool { true } } public enum False: Source { public static var defaultValue: Bool { false } } public enum EmptyString: Source { public static var defaultValue: String { "" } } public enum EmptyList: Source { public static var defaultValue: T { [] } } public enum EmptyMap: Source { public static var defaultValue: T { [:] } } public enum EmptyPlaceholder: Source { public static var defaultValue: T { .empty } } public enum FirstCase: Source { public static var defaultValue: T { T.allCases.first! } } } } public extension DecodableDefault { typealias Zero = Wrapper typealias True = Wrapper typealias False = Wrapper typealias EmptyString = Wrapper typealias EmptyList = Wrapper> typealias EmptyMap = Wrapper> typealias EmptyPlaceholder = Wrapper> typealias FirstCase = Wrapper> } extension DecodableDefault.Wrapper: Equatable where Value: Equatable {} extension DecodableDefault.Wrapper: Hashable where Value: Hashable {} extension DecodableDefault.Wrapper: Encodable where Value: Encodable { public func encode(to encoder: Encoder) throws { var container = encoder.singleValueContainer() try container.encode(wrappedValue) } }