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.
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:
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.
Thanks for a really clear and helpful article. My only feedback would be could you add a pros and cons section vs the alternative? Ie JSONSerialization
Awesome tutorial! I think there may be a problem with the download - I only get two files in a “codable” directory - starter and final. But you reference this: “Open Snake case vs camel case”
I see no other projects/files and tried the download a few times. Is there a link missing, or are the files missing from the download, or am I just missing something else? Thanks.
@rbaker Really glad you like it. Each playground actually has multiple pages after all. Make sure the Project Navigator is visible in Xcode by going to View/Navigators/Show Project Navigator to see them. I hope this helps. Please let me know if you have any other questions or issues about the whole thing when you get a chance. Thank you! :]
Ha! How could I NOT have checked that! Indeed, my error. Thanks again, and thanks for the great job on this tutorial. Awesome that you covered more than jus the basic encode/decode.