gpt4 book ai didi

json - Swift Decodable 的可失败初始化器

转载 作者:可可西里 更新时间:2023-11-01 01:59:48 25 4
gpt4 key购买 nike

我正在尝试解析以下 json 模式,海报可能为空也可能不为空

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

我的可解码类如下:

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

我的问题是如何让海报成为可选的?我的想法是我需要一个可失败的初始化程序,但 decodable 需要一个抛出的初始化程序。

最佳答案

所以看起来我需要添加一个尝试?在推荐列表中 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)
}
}

关于json - Swift Decodable 的可失败初始化器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47598866/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com