Я создал расширение KeyedDecodingContainer для возврата моего пользовательского объекта (Decodable) с нулевым свойством.
func decodeIfPresentOrNullify<T>(_ type: T.Type, forKey key: KeyedDecodingContainer<K>.Key) throws -> T? where T : MyObject {
if contains(key) {
let nilObject: Bool = try decodeNil(forKey: key)
if nilObject == false {
return try decodeIfPresent(type, forKey: key)
}
else {
return T.init(nulled: true)
}
}
return nil
}
Как улучшить эту функцию для обработки объекта или массива. как public func decodeIfPresent<T>(_ type: T.Type, forKey key: KeyedDecodingContainer<K>.Key) throws -> T? where T : Decodable
делает для Decodable?
Класс MyObject выглядит примерно так:
class MyObject: NSObject, Decodable, Encodable, NSCoding {
//MARK: Publics
public var isNulled: Bool = false
//MARK: LifeCycle
required public init(nulled: Bool) {
super.init()
isNulled = nulled
}
@objc public override init() {
super.init()
}
//Some more code...
}
и мой нужный код должен обрабатывать это
myObjectSubclassInstance = try container.decodeIfPresentOrNullify(MyObjectSubclass.self, forKey: . myObjectSubclassKey)
а также
myObjectSubclassInstance = try container.decodeIfPresentOrNullify([MyObjectSubclass].self, forKey: . myObjectSubclassKey)