To convert Codable to Dictionary I have created this extension.
extension Encodable {
func asDictionary() throws -> [String: Any] {
let data = try JSONEncoder().encode(self)
guard let dictionary = try JSONSerialization.jsonObject(with: data, options: .allowFragments) as? [String: Any] else {
throw NSError()
}
return dictionary
}
}
But I have special requirement like below.
struct Foo: Codable {
let a: Foo1?
let b: Foo2?
}
struct Foo1: Codable{
let x:String
}
struct Foo2: Codable{
let y:String
}
let foo: Foo = Foo(a:Foo1(x:"hello"),b: nil)
let dict = foo.asDictionary
Actual Output : {a:{x:hello}}
Excepted Output : {a:{x:hello,y:nil}}
How we can do this getting key with nil values?