Skip to content

Commit 85096bd

Browse files
committed
Implement DefaultCodable decode implementation to default when key is not present
1 parent b746807 commit 85096bd

File tree

1 file changed

+15
-0
lines changed

1 file changed

+15
-0
lines changed

Sources/BetterCodable/DefaultCodable.swift

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -30,3 +30,18 @@ public struct DefaultCodable<Default: DefaultCodableStrategy>: Codable {
3030

3131
extension DefaultCodable: Equatable where Default.RawValue: Equatable { }
3232
extension DefaultCodable: Hashable where Default.RawValue: Hashable { }
33+
34+
// MARK: - KeyedDecodingContainer
35+
public extension KeyedDecodingContainer {
36+
37+
/// Default implementation of decoding a DefaultCodable
38+
///
39+
/// Decodes successfully if key is available if not fallsback to the default value provided.
40+
func decode<P>(_: DefaultCodable<P>.Type, forKey key: Key) throws -> DefaultCodable<P> {
41+
if let value = try decodeIfPresent(DefaultCodable<P>.self, forKey: key) {
42+
return value
43+
} else {
44+
return DefaultCodable(wrappedValue: P.defaultValue)
45+
}
46+
}
47+
}

0 commit comments

Comments
 (0)