Created
December 20, 2019 14:50
-
-
Save jordanebelanger/8469d397dc43018edfc7641e871460b9 to your computer and use it in GitHub Desktop.
This file contains 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
import Foundation | |
enum Nullable<Value: Codable>: Codable { | |
case some(_ value: Value) | |
case null | |
init(from decoder: Decoder) throws { | |
let container = try decoder.singleValueContainer() | |
if container.decodeNil() { | |
self = .null | |
} else { | |
self = .some(try container.decode(Value.self)) | |
} | |
} | |
func encode(to encoder: Encoder) throws { | |
var container = encoder.singleValueContainer() | |
switch self { | |
case .some(let value): | |
try container.encode(value) | |
case .null: | |
try container.encodeNil() | |
} | |
} | |
} | |
struct SomePatchRequest: Codable { | |
var nullableIntProperty: Nullable<Int>? | |
} | |
let json = #"{"nullableIntProperty": null}"# | |
//let json = #"{}"# | |
let data = json.data(using: .utf8)! | |
// The `Nullable` decode function won't be called since null is treated the same as if the value was missing entirely | |
// and therefore does not need to be decoded. | |
let patchRequest = try JSONDecoder().decode(SomePatchRequest.self, from: data) | |
print(patchRequest) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
You can achieve this using a custom decoder for the parent object like this
Is there a better way?