Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

iOS Parsing JSON Using Codable Parsing Different JSON Structures Recap: Parsing Different JSON Structures

Raymond Choy
.a{fill-rule:evenodd;}techdegree seal-36
Raymond Choy
iOS Development with Swift Techdegree Graduate 11,187 Points

I need help Parsing JSON Using Codable to account for missing “imdb_url” using Swift

/* This is literally the only Swift code challenge that no one has ever posted the answer for anywhere in Treehouse or the whole internet searching Google.

Someone referred me to a video and i watched it and tried 5 more solutions that also didn't work Please help, if anyone knows that solution... Thanks */

let json = """ { "title": "Tomb Raider", "genre": "action", "imdb_url": "https://www.imdb.com/title/tt1365519" } """.data(using: .utf8)!

struct Movie: Codable { let title: String let genre: String let imdbUrl: String?

enum CodingKeys: String, CodingKey {
    case title
    case genre
    case imdbUrl = "imdb_url"

init(from decoder: Decoder) throws {
    let container = try decoder.container(keyedBy: CodingKeys.self)
    self.title = try container.decode(String.self, forKey: .title)
    self.genre = try container.decode(String.self, forKey: .genre)
    self.imdbUrl = try ___________


/* I have tried the following answers all of which fail to pass the challenge:

innerContainer.decodeIfPresent(String.self, forKey: .imdbUrl

container.decodeIfPresent(String.self, forKey, .imdbUrl)

container.decode(String?.self, forKey, .imdbUrl)

container.decodeIfPresent(String?.self, forKey, .imdbUrl)

innerContainer.decodeIfPresent(String?.self, forKey: .imdbUrl)

innerContainer.decodeIfPresent(String.self, forKey: .imdbUrl)

innerContainer.decode(String?.self, forKey: .imdbUrl)


1 Answer

Raymond Choy
.a{fill-rule:evenodd;}techdegree seal-36
Raymond Choy
iOS Development with Swift Techdegree Graduate 11,187 Points

Thanks to no help from Treehouse, someone from Stackoverflow helped me figure out the following code that has passed the challenge:

container.decodeIfPresent(String.self, forKey: .imdbUrl)