I have such an object that should be encoded to JSON (My Playground example)
struct Toy: Codable {
var name: String
enum GiftKeys: String, CodingKey {
case toy = "name"
}
func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: GiftKeys.self)
try container.encode(self, forKey: .toy)
}
}
struct Employee: Encodable {
var name: String
var id: Int
var favoriteToy: Toy
enum CodingKeys: CodingKey {
case name, id
}
func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: CodingKeys.self)
try container.encode(name, forKey: .name)
try container.encode(id, forKey: .id)
try favoriteToy.encode(to: encoder)
}
}
do {
let toy = Toy(name: "Teddy Bear")
let employee = Employee(name: "John Appleseed", id: 7, favoriteToy: toy)
let encoder = JSONEncoder()
let nestedData: Data = try encoder.encode(employee)
let nestedString = String(data: nestedData, encoding: .utf8)!
print(nestedString)
}
What I am going to achieve is that each object knows how to encode itself. So, in my example when I through the employee object to the encoder, so each of the objects (employee and Toy) is responsible for its encoding.
But when I try to run the example in the Playground looks like it comes to the stuck in the line try favoriteToy.encode(to: encoder)
What is the problem here?