Using Property Wrappers with Codable

Use an extension on KeyedDecodingContainer and add an overload for decode method like this:

extension KeyedDecodingContainer {

    func decode<T>(_ type: StringRepresentation <T?>.Type, forKey key: Self.Key) throws -> StringRepresentation <T?> where T : Decodable {
        return try decodeIfPresent(type, forKey: key) ?? StringRepresentation <T?>(wrappedValue: nil)
    }
}

This will make sure that your synthesised property _value which is a non-optional is always created but in case the key is not present in json it only wraps around a nil value.

This works with synthesised Codable initialiser as this overloaded decode is used instead of its generic counterpart as it has a concrete type which is preferred over a generic one if present.

9 Likes