-
-
Save andreyz/157cc159de0089a213ba7e5ac4d3cc28 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