Skip to content

Instantly share code, notes, and snippets.

@0xMarK
Created October 20, 2023 08:12
Show Gist options
  • Save 0xMarK/24a212b5f31422aa8f4dc4af71d9b715 to your computer and use it in GitHub Desktop.
Save 0xMarK/24a212b5f31422aa8f4dc4af71d9b715 to your computer and use it in GitHub Desktop.
Property wrapper to turn empty collection into nil
import Foundation
@propertyWrapper
struct EmptyToNil<WrappedType: Codable & Collection>: Codable {
let wrappedValue: WrappedType?
init(wrappedValue: WrappedType?) {
self.wrappedValue = wrappedValue
}
init(from decoder: Decoder) throws {
let container = try decoder.singleValueContainer()
guard let value = try? container.decode(WrappedType.self) else {
wrappedValue = nil
return
}
wrappedValue = value.isEmpty ? nil : value
}
func encode(to encoder: Encoder) throws {
try wrappedValue.encode(to: encoder)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment