Created
February 7, 2021 03:09
-
-
Save IanKeen/4b415861b932f8fdf2e39e115df5ede4 to your computer and use it in GitHub Desktop.
PropertyWrapper: Ignore codable properties
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) | |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
@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