Cory
Cory

Reputation: 2312

A failable initialiizer for Swift Decodable

I'm attempting to parse the following json schema, poster may or may not be empty

{
  "poster": {},
  "recommends": []
}

My decodable classes are as follows:

public struct RecommendedList: Decodable {
    public let poster: Poster?
    public let recommends: [Recommend]
}

public struct Poster: Decodable {
    public let backgroundImage: URL
    public let topImage: URL
    public let windowImage: URL
    public let windowSkinImagePath: URL
    public let deeplink: URL

    public init(from decoder: Decoder) throws {
        // I want a failable intializer not one that throws
    }
}

My question is how do I make poster optional? My thought was I would need a failable initializer, but decodable requires a init that throws.

Upvotes: 3

Views: 1518

Answers (1)

Cory
Cory

Reputation: 2312

so it looks like I needed to add a try? in the Recommended List init(from decoder:)

public struct RecommendedList: Decodable {
    public let poster: Poster?
    public let recommends: [Recommend]

    enum CodingKeys: String, CodingKey {
        case poster
        case recommends
    }

    public init(from decoder: Decoder) throws {
        let container = try decoder.container(keyedBy: CodingKeys.self)
        poster = try? container.decode(Poster.self, forKey: .poster)
        recommends = try container.decode([Recommend].self, forKey: .recommends)
    }
}

Upvotes: 2

Related Questions