TemplateVariable.swift 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. // Copyright 2025 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. enum TemplateVariable: Encodable, Sendable {
  16. case string(String)
  17. case int(Int)
  18. case double(Double)
  19. case bool(Bool)
  20. case array([TemplateVariable])
  21. case dictionary([String: TemplateVariable])
  22. init(value: Any) throws {
  23. switch value {
  24. case let value as String:
  25. self = .string(value)
  26. case let value as Int:
  27. self = .int(value)
  28. case let value as Double:
  29. self = .double(value)
  30. case let value as Bool:
  31. self = .bool(value)
  32. case let value as [Any]:
  33. self = try .array(value.map { try TemplateVariable(value: $0) })
  34. case let value as [String: Any]:
  35. self = try .dictionary(value.mapValues { try TemplateVariable(value: $0) })
  36. default:
  37. throw EncodingError.invalidValue(
  38. value,
  39. EncodingError.Context(codingPath: [], debugDescription: "Invalid value")
  40. )
  41. }
  42. }
  43. func encode(to encoder: Encoder) throws {
  44. var container = encoder.singleValueContainer()
  45. switch self {
  46. case let .string(value):
  47. try container.encode(value)
  48. case let .int(value):
  49. try container.encode(value)
  50. case let .double(value):
  51. try container.encode(value)
  52. case let .bool(value):
  53. try container.encode(value)
  54. case let .array(value):
  55. try container.encode(value)
  56. case let .dictionary(value):
  57. try container.encode(value)
  58. }
  59. }
  60. }