add unkeyedcontainer

This commit is contained in:
panxi 2019-11-22 14:33:42 -05:00
parent 1b99abdb6e
commit 0d1c3196bf
2 changed files with 23 additions and 2 deletions

View File

@ -10,7 +10,7 @@ import Foundation
public protocol Model: Codable {
static var identifier: String { get set }
static var identifier: String { get }
}

View File

@ -24,6 +24,27 @@ public struct ModelRegistry {
}
}
extension UnkeyedDecodingContainer {
public mutating func decodeUnKeyedIfPresent<T, C:CodingKey>(_ type: T.Type, typeCodingKey: C) throws -> T? where T : Decodable {
let meta = try self.nestedContainer(keyedBy: C.self)
guard let type = try meta.decodeIfPresent(String.self, forKey: typeCodingKey) else {
return nil
}
//get the type
guard let found = ModelRegistry.types[type] else {
throw ModelRegistry.Error.decoderErrorModelNotMapped
}
let model = try self.decode(found)
guard let m = model as? T else {
throw ModelRegistry.Error.decoderError
}
return m
}
}
extension KeyedDecodingContainer where Key: CodingKey {
@ -48,7 +69,7 @@ extension KeyedDecodingContainer where Key: CodingKey {
public func decodeIfPresent<T, C:CodingKey>(codingKey: KeyedDecodingContainer<K>.Key, typeCodingKey: C) throws -> T? {
//get the type string
let meta = try self.nestedContainer(keyedBy: type(of: typeCodingKey), forKey: codingKey)
let meta = try self.nestedContainer(keyedBy: C.self, forKey: codingKey)
guard let type = try meta.decodeIfPresent(String.self, forKey: typeCodingKey) else {
return nil
}