TemplateInput.swift 2.0 KB

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