Last active
June 18, 2024 10:33
-
-
Save jordanebelanger/0f48bc7276be98ed688d620f59b17b67 to your computer and use it in GitHub Desktop.
Codable enum that will differentiate between an explicitly null value vs the value being missing, useful for PATCH request etc
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
enum Nullable<T>: Codable where T: Codable { | |
case some(_ value: T) | |
case null | |
case undefined | |
init(from decoder: Decoder) throws { | |
let container = try decoder.singleValueContainer() | |
if container.decodeNil() { | |
self = .null | |
} else { | |
self = try .some(container.decode(T.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() | |
case .undefined: | |
break | |
} | |
} | |
} | |
extension KeyedEncodingContainer { | |
mutating func encode<T>(_ value: Nullable<T>, forKey key: KeyedEncodingContainer<K>.Key) throws where T : Encodable { | |
switch value { | |
case .some(let value): | |
try self.encode(value, forKey: key) | |
case .null: | |
try self.encodeNil(forKey: key) | |
case .undefined: | |
break | |
} | |
} | |
} | |
extension KeyedDecodingContainer { | |
func decode<T>(_ type: Nullable<T>.Type, forKey key: KeyedDecodingContainer<K>.Key) throws -> Nullable<T> { | |
if !self.contains(key) { | |
return .undefined | |
} else if try self.decodeNil(forKey: key) { | |
return .null | |
} else { | |
return try .some(self.decode(T.self, forKey: key)) | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment