Group Group Group Group Group Group Group Group Group

Encoding and Decoding in Swift | raywenderlich.com

In this tutorial, you’ll learn all about encoding and decoding in Swift, exploring the basics and advanced topics like custom dates and custom encoding.


This is a companion discussion topic for the original entry at https://www.raywenderlich.com/3418439-encoding-and-decoding-in-swift

Great article, thank you for sharing. But I seems found ambiguous syntax in Working With Deep JSON Hierarchies section. In encode function and following syntax:

giftContainer.encode(toy, forKey: .toy)

toy must be replaced to gift, because toy is global variable from outside Employee class instead gift is instance variable of Employee. Revised syntax:

giftContainer.encode(gift, forKey: .toy)

Thank you for the tutorial!
I found a typo in the section, “Working With Deep JSON Hierarchies”.

enum CodingKeys: CodingKey {
case name, id, gift
}
// 2
enum GiftKeys: CodingKey {
case toy
}
// 3
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)
// 4
var giftContainer = container
.nestedContainer(keyedBy: GiftKeys.self, forKey: .gift)
try giftContainer.encode(toy, forKey: .toy)
}

The last line: try giftContainer.encode(toy, forKey: .toy),
should be: try giftContainer.encode(favoriteToy, forKey: .toy).
The favoriteToy was mistyped to toy.

I think I also found a typo, in working with flat JSON hierarchies where it talks mapping the swift object “favoriteToy” to the JSON key “gift” it instead references the object “toy” down below.

I believe that

        try container.encode(toy.name, forKey: .gift)

should be

        try container.encode(favoriteToy.name, forKey: .gift)

@shogunkaramazov Great Article. I want to know how codable perform downcasting if possible. For example, In java

{
    id: 1,
    name: "MyName",
    ...
}

this above json convert into object like

class Employee {
    String id;
    String name;
    ...
}

If I decode network call which contains Int, but I use String to convert, it throws an error.
Is there any way that could happen?