gpt4 book ai didi

ios - Codable - 如何用空数组声明可选数组类型

转载 作者:行者123 更新时间:2023-11-28 20:49:56 27 4
gpt4 key购买 nike

struct Data: Codable {
let name: String?
let dataArray: [User] = [User]()
}

dataArray 是可选的,所以我想用空分配它但我的 Codable 失败了?我能知道如何实现这一点吗,我可以在不分配它的情况下将其声明为可选。但我想实现这一目标。

最佳答案

您应该手动解码您的对象:

struct Data: Codable {
let name: String?
let dataArray: [User]

enum Keys: String, CodingKey {
case name
case dataArray
}

init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: Keys.self)
name = try? container.decode(String.self, forKey: .name)
dataArray = (try? container.decode(User, forKey: . dataArray)) ?? []
}
}

或者您可以创建一个包装器:

struct Data: Codable {
let name: String?
private let _dataArray: [User]?

var dataArray : [User] {
get {
return _dataArray ?? []
}
}

enum Keys: String, CodingKey {
case name
case dataArray
}
}

关于ios - Codable - 如何用空数组声明可选数组类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59085329/

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