Skip to content

Instantly share code, notes, and snippets.

@IanKeen
Created February 7, 2021 03:09
Show Gist options
  • Star 6 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save IanKeen/4b415861b932f8fdf2e39e115df5ede4 to your computer and use it in GitHub Desktop.
Save IanKeen/4b415861b932f8fdf2e39e115df5ede4 to your computer and use it in GitHub Desktop.
PropertyWrapper: Ignore codable properties
struct Foo: Codable {
var name: String
@Ignore var foo: Int?
}
let model = Foo(name: "Ian", foo: 42)
let data = try! JSONEncoder().encode(model)
print(String(data: data, encoding: .utf8)!) // {"name":"Ian"}
let json = """
{"name":"Ian","foo":42}
"""
let model = try! JSONDecoder().decode(Foo.self, from: Data(json.utf8))
print(model) // Foo(name: "Ian", foo: 42)
@propertyWrapper
struct Ignore<T> {
var wrappedValue: T
}
extension Ignore: Encodable where T: Encodable { }
extension Ignore: Decodable where T: Decodable { }
extension KeyedEncodingContainer {
mutating func encode<T: Encodable>(_ value: Ignore<T>, forKey key: KeyedEncodingContainer<K>.Key) throws { }
}
extension KeyedDecodingContainer {
func decode<T: Decodable>(_ type: Ignore<T?>.Type, forKey key: KeyedDecodingContainer<K>.Key) throws -> Ignore<T?> {
return try .init(wrappedValue: decodeIfPresent(T.self, forKey: key))
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment