OptionalVarWrapper.swift 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. // Copyright 2024 Google LLC
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. import Foundation
  15. @available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *)
  16. @propertyWrapper
  17. public struct OptionalVariable<Value> where Value: Encodable {
  18. public private(set) var isSet: Bool = false
  19. public var wrappedValue: Value? {
  20. didSet {
  21. isSet = true
  22. }
  23. }
  24. // init called when var isn't initialized
  25. // it is important to define this otherwise the var gets initialized with nil value
  26. public init() {
  27. wrappedValue = nil
  28. isSet = false
  29. }
  30. // init called with explicit initialization either with nil or value
  31. public init(wrappedValue initialValue: Value?) {
  32. wrappedValue = initialValue
  33. isSet = true
  34. }
  35. public var projectedValue: Self {
  36. return self
  37. }
  38. }
  39. @available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *)
  40. extension OptionalVariable: Encodable {
  41. public func encode(to encoder: Encoder) throws {
  42. if isSet {
  43. var container = encoder.singleValueContainer()
  44. try container.encode(wrappedValue)
  45. }
  46. }
  47. }