ExplicitNull.swift 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  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 around a `Optional` such that it explicitly sets the corresponding document field
  18. /// to Null, instead of not setting the field at all.
  19. ///
  20. /// When encoded into a Firestore document by `Firestore.Encoder`, an `Optional` field with
  21. /// `nil` value will be skipped, so the resulting document simply will not have the field.
  22. ///
  23. /// When setting the field to `Null` instead of skipping it is desired, `ExplicitNull` can be
  24. /// used instead of `Optional`.
  25. public enum ExplicitNull<Wrapped> {
  26. case none
  27. case some(Wrapped)
  28. /// Create a `ExplicitNull` object from `Optional`.
  29. public init(_ optional: Wrapped?) {
  30. switch optional {
  31. case .none:
  32. self = .none
  33. case let .some(wrapped):
  34. self = .some(wrapped)
  35. }
  36. }
  37. /// Get the `Optional` representation of `ExplicitNull`.
  38. public var value: Wrapped? {
  39. switch self {
  40. case .none:
  41. return .none
  42. case let .some(wrapped):
  43. return .some(wrapped)
  44. }
  45. }
  46. }
  47. extension ExplicitNull: Equatable where Wrapped: Equatable {}
  48. extension ExplicitNull: Encodable where Wrapped: Encodable {
  49. public func encode(to encoder: Encoder) throws {
  50. var container = encoder.singleValueContainer()
  51. switch self {
  52. case .none:
  53. try container.encodeNil()
  54. case let .some(wrapped):
  55. try container.encode(wrapped)
  56. }
  57. }
  58. }
  59. extension ExplicitNull: Decodable where Wrapped: Decodable {
  60. public init(from decoder: Decoder) throws {
  61. let container = try decoder.singleValueContainer()
  62. if container.decodeNil() {
  63. self = .none
  64. } else {
  65. self = .some(try container.decode(Wrapped.self))
  66. }
  67. }
  68. }