Skip to content

Instantly share code, notes, and snippets.

@Akhu
Created May 11, 2018 09:46
Show Gist options
  • Save Akhu/029b07159e0414bfc8fc3e8bec4a53bf to your computer and use it in GitHub Desktop.
Save Akhu/029b07159e0414bfc8fc3e8bec4a53bf to your computer and use it in GitHub Desktop.
A custom codable implementation, especially the test of if the value is double or string or anything and code / decode things
//
// ExtractedData.swift
// AGKitDemo-Template
//
// Created by Anthony on 20/03/2018.
// Copyright © 2018 AboutGoods. All rights reserved.
//
import Foundation
protocol ExtractedDataProtocol {
func getBestValue() -> Any
}
struct ExtractedData {
var value:Any?
var accuracy:Double?
enum CodingKeys: String, CodingKey {
case value = "value"
case accuracy
}
}
extension ExtractedData: Encodable {
func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: CodingKeys.self)
if let doubleValue = self.value as? Double {
try container.encode(doubleValue, forKey: .value)
} else if let stringValue = self.value as? String {
try container.encode(stringValue, forKey: .value)
} else {
let context = DecodingError.Context(codingPath: [CodingKeys.value], debugDescription: "Unrecognized type for value")
throw DecodingError.valueNotFound(ExtractedData.self, context)
}
try container.encode(self.accuracy, forKey: .accuracy)
}
}
extension ExtractedData: Decodable {
init(from decoder: Decoder) throws {
let values = try decoder.container(keyedBy: CodingKeys.self)
if let decodedValue = try? values.decode(Double.self, forKey: .value) {
self.value = decodedValue
} else if let decodedValue = try? values.decode(String.self, forKey: .value){
self.value = decodedValue
} else {
let context = DecodingError.Context(codingPath: [CodingKeys.value], debugDescription: "No concording type found for value")
throw DecodingError.valueNotFound(ExtractedData.self, context)
}
self.accuracy = try values.decode(Double.self, forKey: .accuracy)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment