Created
June 13, 2021 11:24
-
-
Save AlexandrFadeev/7d13b859219b91f6c8ed4e68b6b194d6 to your computer and use it in GitHub Desktop.
Decodable netsted containers
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Product: Decodable { | |
var id: Int | |
var art: String? | |
var title: String? | |
var votesCount: Int | |
var averageRating: Double | |
enum CodingKeys: String, CodingKey { | |
case id | |
case art | |
case title | |
case ratings | |
} | |
enum RatingsCodingKeys: String, CodingKey { | |
case votesCount = "votes_count" | |
case averageRating = "average_rating" | |
} | |
required init(from decoder: Decoder) throws { | |
let container = try decoder.container(keyedBy: CodingKeys.self) | |
self.id = try container.decode(Int.self, forKey: .id) | |
self.art = try? container.decode(String.self, forKey: .art) | |
self.title = try? container.decode(String.self, forKey: .title) | |
// Nested ratings | |
let ratingsContainer = try container.nestedContainer(keyedBy: RatingsCodingKeys.self, forKey: .ratings) | |
self.votesCount = try ratingsContainer.decode(Int.self, forKey: .votesCount) | |
self.averageRating = try ratingsContainer.decode(Double.self, forKey: .averageRating) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment