Created
October 20, 2023 08:12
-
-
Save 0xMarK/24a212b5f31422aa8f4dc4af71d9b715 to your computer and use it in GitHub Desktop.
Property wrapper to turn empty collection into nil
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
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