Guest User

Untitled

a guest
May 16th, 2018
154
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.87 KB | None | 0 0
  1. //
  2. // ExtractedData.swift
  3. // AGKitDemo-Template
  4. //
  5. // Created by Anthony on 20/03/2018.
  6. // Copyright © 2018 AboutGoods. All rights reserved.
  7. //
  8.  
  9. import Foundation
  10.  
  11. protocol ExtractedDataProtocol {
  12. func getBestValue() -> Any
  13. }
  14.  
  15. struct ExtractedData {
  16. var value:Any?
  17. var accuracy:Double?
  18.  
  19. enum CodingKeys: String, CodingKey {
  20. case value = "value"
  21. case accuracy
  22. }
  23.  
  24. }
  25.  
  26. extension ExtractedData: Encodable {
  27. func encode(to encoder: Encoder) throws {
  28. var container = encoder.container(keyedBy: CodingKeys.self)
  29.  
  30. if let doubleValue = self.value as? Double {
  31.  
  32. try container.encode(doubleValue, forKey: .value)
  33.  
  34. } else if let stringValue = self.value as? String {
  35.  
  36. try container.encode(stringValue, forKey: .value)
  37.  
  38. } else {
  39.  
  40. let context = DecodingError.Context(codingPath: [CodingKeys.value], debugDescription: "Unrecognized type for value")
  41. throw DecodingError.valueNotFound(ExtractedData.self, context)
  42. }
  43.  
  44. try container.encode(self.accuracy, forKey: .accuracy)
  45. }
  46. }
  47.  
  48. extension ExtractedData: Decodable {
  49. init(from decoder: Decoder) throws {
  50. let values = try decoder.container(keyedBy: CodingKeys.self)
  51.  
  52. if let decodedValue = try? values.decode(Double.self, forKey: .value) {
  53. self.value = decodedValue
  54.  
  55. } else if let decodedValue = try? values.decode(String.self, forKey: .value){
  56. self.value = decodedValue
  57.  
  58. } else {
  59.  
  60. let context = DecodingError.Context(codingPath: [CodingKeys.value], debugDescription: "No concording type found for value")
  61. throw DecodingError.valueNotFound(ExtractedData.self, context)
  62. }
  63.  
  64. self.accuracy = try values.decode(Double.self, forKey: .accuracy)
  65. }
  66. }
Add Comment
Please, Sign In to add comment