Codable.swift 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. /*
  2. * Copyright 2021 Google LLC
  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 Foundation
  17. import FirebaseRemoteConfig
  18. import FirebaseSharedSwift
  19. public enum RemoteConfigCodableError: Error {
  20. case jsonValueError
  21. }
  22. public extension RemoteConfigValue {
  23. /**
  24. * Extracts a RemoteConfigValue JSON-encoded object and decodes it to the requested type
  25. *
  26. * - Parameter valueType: The type to decode the JSON-object to
  27. */
  28. func decoded<Value: Decodable>(asType: Value.Type = Value.self) throws -> Value {
  29. guard let jsonValue = self.jsonValue else {
  30. throw RemoteConfigCodableError.jsonValueError
  31. }
  32. return try FirebaseDataDecoder().decode(Value.self, from: jsonValue)
  33. }
  34. }
  35. public extension RemoteConfig {
  36. /**
  37. * Sets config defaults from an encodable struct.
  38. *
  39. * - Parameter value: The object to use to set the defaults.
  40. */
  41. func setDefaults<Value: Encodable>(from value: Value) throws {
  42. let encoded = try FirebaseDataEncoder().encode(value) as! [String: NSObject]
  43. setDefaults(encoded)
  44. }
  45. }