ExplicitNull.swift 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. /*
  2. * Copyright 2019 Google
  3. *
  4. * Licensed under the Apache License, Version 2.0 (the "License");
  5. * you may not use this file except in compliance with the License.
  6. * You may obtain a copy of the License at
  7. *
  8. * http://www.apache.org/licenses/LICENSE-2.0
  9. *
  10. * Unless required by applicable law or agreed to in writing, software
  11. * distributed under the License is distributed on an "AS IS" BASIS,
  12. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. * See the License for the specific language governing permissions and
  14. * limitations under the License.
  15. */
  16. import FirebaseFirestore
  17. /// Wraps an `Optional` field in a `Codable` object such that when the field
  18. /// has a `nil` value it will encode to a null value in Firestore. Normally,
  19. /// optional fields are omitted from the encoded document.
  20. ///
  21. /// This is useful for ensuring a field is present in a Firestore document,
  22. /// even when there is no associated value.
  23. @propertyWrapper
  24. public struct ExplicitNull<Value> {
  25. var value: Value?
  26. public init(wrappedValue value: Value?) {
  27. self.value = value
  28. }
  29. public var wrappedValue: Value? {
  30. get { value }
  31. set { value = newValue }
  32. }
  33. }
  34. extension ExplicitNull: Equatable where Value: Equatable {}
  35. extension ExplicitNull: Hashable where Value: Hashable {}
  36. extension ExplicitNull: Encodable where Value: Encodable {
  37. public func encode(to encoder: Encoder) throws {
  38. var container = encoder.singleValueContainer()
  39. if let value = value {
  40. try container.encode(value)
  41. } else {
  42. try container.encodeNil()
  43. }
  44. }
  45. }
  46. extension ExplicitNull: Decodable where Value: Decodable {
  47. public init(from decoder: Decoder) throws {
  48. let container = try decoder.singleValueContainer()
  49. if container.decodeNil() {
  50. value = nil
  51. } else {
  52. value = try container.decode(Value.self)
  53. }
  54. }
  55. }