ExplicitNull.swift 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  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. #if SWIFT_PACKAGE
  17. @_exported import FirebaseFirestoreInternalWrapper
  18. #else
  19. @_exported import FirebaseFirestoreInternal
  20. #endif // SWIFT_PACKAGE
  21. /// Wraps an `Optional` field in a `Codable` object such that when the field
  22. /// has a `nil` value it will encode to a null value in Firestore. Normally,
  23. /// optional fields are omitted from the encoded document.
  24. ///
  25. /// This is useful for ensuring a field is present in a Firestore document,
  26. /// even when there is no associated value.
  27. @propertyWrapper
  28. public struct ExplicitNull<Value> {
  29. var value: Value?
  30. public init(wrappedValue value: Value?) {
  31. self.value = value
  32. }
  33. public var wrappedValue: Value? {
  34. get { value }
  35. set { value = newValue }
  36. }
  37. }
  38. extension ExplicitNull: Equatable where Value: Equatable {}
  39. extension ExplicitNull: Hashable where Value: Hashable {}
  40. extension ExplicitNull: Encodable where Value: Encodable {
  41. public func encode(to encoder: Encoder) throws {
  42. var container = encoder.singleValueContainer()
  43. if let value {
  44. try container.encode(value)
  45. } else {
  46. try container.encodeNil()
  47. }
  48. }
  49. }
  50. extension ExplicitNull: Decodable where Value: Decodable {
  51. public init(from decoder: Decoder) throws {
  52. let container = try decoder.singleValueContainer()
  53. if container.decodeNil() {
  54. value = nil
  55. } else {
  56. value = try container.decode(Value.self)
  57. }
  58. }
  59. }