/ / Un inizializzatore disponibile per Swift Decodable - json, swift, decodable

Un inizializzatore utilizzabile per Swift Decodable - json, swift, decodable

Sto tentando di analizzare il seguente schema json, il poster può o non può essere vuoto

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

Le mie classi decodificabili sono le seguenti:

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
}
}

La mia domanda è: come posso rendere opzionale il poster? Il mio pensiero era che avrei avuto bisogno di un inizializzatore, ma decodificabile richiede un init che lancia.

risposte:

0 per risposta № 1

quindi sembra che ho bisogno di aggiungere una prova? nella lista degli indirizzi consigliati (dal decodificatore :)

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)
}
}