add unkeyedcontainer
This commit is contained in:
parent
1b99abdb6e
commit
0d1c3196bf
@ -10,7 +10,7 @@ import Foundation
|
|||||||
|
|
||||||
public protocol Model: Codable {
|
public protocol Model: Codable {
|
||||||
|
|
||||||
static var identifier: String { get set }
|
static var identifier: String { get }
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@ -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 {
|
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? {
|
public func decodeIfPresent<T, C:CodingKey>(codingKey: KeyedDecodingContainer<K>.Key, typeCodingKey: C) throws -> T? {
|
||||||
|
|
||||||
//get the type string
|
//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 {
|
guard let type = try meta.decodeIfPresent(String.self, forKey: typeCodingKey) else {
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|||||||
Loading…
Reference in New Issue
Block a user