You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

76 lines
2.3 KiB

  1. //
  2. // DictionaryTransform.swift
  3. // ObjectMapper
  4. //
  5. // Created by Milen Halachev on 7/20/16.
  6. //
  7. // Copyright (c) 2014-2018 Tristan Himmelman
  8. //
  9. // Permission is hereby granted, free of charge, to any person obtaining a copy
  10. // of this software and associated documentation files (the "Software"), to deal
  11. // in the Software without restriction, including without limitation the rights
  12. // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  13. // copies of the Software, and to permit persons to whom the Software is
  14. // furnished to do so, subject to the following conditions:
  15. //
  16. // The above copyright notice and this permission notice shall be included in
  17. // all copies or substantial portions of the Software.
  18. //
  19. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  20. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  21. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  22. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  23. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  24. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  25. // THE SOFTWARE.
  26. import Foundation
  27. ///Transforms [String: AnyObject] <-> [Key: Value] where Key is RawRepresentable as String, Value is Mappable
  28. public struct DictionaryTransform<Key, Value>: TransformType where Key: Hashable, Key: RawRepresentable, Key.RawValue == String, Value: Mappable {
  29. public init() {
  30. }
  31. public func transformFromJSON(_ value: Any?) -> [Key: Value]? {
  32. guard let json = value as? [String: Any] else {
  33. return nil
  34. }
  35. let result = json.reduce([:]) { (result, element) -> [Key: Value] in
  36. guard
  37. let key = Key(rawValue: element.0),
  38. let valueJSON = element.1 as? [String: Any],
  39. let value = Value(JSON: valueJSON)
  40. else {
  41. return result
  42. }
  43. var result = result
  44. result[key] = value
  45. return result
  46. }
  47. return result
  48. }
  49. public func transformToJSON(_ value: [Key: Value]?) -> Any? {
  50. let result = value?.reduce([:]) { (result, element) -> [String: Any] in
  51. let key = element.0.rawValue
  52. let value = element.1.toJSON()
  53. var result = result
  54. result[key] = value
  55. return result
  56. }
  57. return result
  58. }
  59. }