38 lines
1.2 KiB
Swift
38 lines
1.2 KiB
Swift
//
|
|
// ResponseResult.swift
|
|
// Cyberlock
|
|
//
|
|
// Created by Jura on 8/21/19.
|
|
// Copyright © 2019 Omicronmedia. All rights reserved.
|
|
//
|
|
|
|
import Foundation
|
|
|
|
let decodingContext = CodingUserInfoKey(rawValue: "keyPath")!
|
|
|
|
internal struct ResponseResult<T: Decodable>: Decodable {
|
|
|
|
let result: T
|
|
|
|
struct ResponseResultKey: CodingKey {
|
|
var stringValue: String
|
|
init(stringValue: String) {
|
|
self.stringValue = stringValue
|
|
}
|
|
var intValue: Int? { return nil }
|
|
init?(intValue: Int) { return nil }
|
|
}
|
|
|
|
init(from decoder: Decoder) throws {
|
|
let container = try decoder.container(keyedBy: ResponseResultKey.self)
|
|
guard let keyPath = decoder.userInfo[decodingContext] as? String
|
|
, let matchedKey = container.allKeys.filter({ $0.stringValue == keyPath }).first else {
|
|
throw DecodingError.dataCorruptedError(forKey: ResponseResultKey.init(stringValue: decodingContext.rawValue),
|
|
in: container,
|
|
debugDescription: "Keypath \(decodingContext.rawValue) not found")
|
|
}
|
|
self.result = try container.decode(T.self, forKey: matchedKey)
|
|
}
|
|
|
|
}
|