gpt4 book ai didi

ios - 在 Decodable 协议(protocol)中为模型数组设置容量

转载 作者:行者123 更新时间:2023-11-28 23:24:18 26 4
gpt4 key购买 nike

如果用户没有登录,即使 JSON 响应包含更多记录,我也想设置模型数组的最大容量。

public class AlertsInbox: Codable {
public var messages: [Messages]?
public init(messages: [Messages]) {
self.messages = messages
if !GlobalVar.isLoggedIn,
let capacity = GlobalVar.messageCapacity {
self.messages?.reserveCapacity(capacity)
}
}
}

解码 json 响应:

let responseMessage = try JSONDecoder().decode(AlertsInbox.self, from: data)

在模型的初始化中使用 reserveCapacity,但它会被响应中收到的记录数覆盖。

解码时如何限制?

谢谢

最佳答案

您不应在 Type 的初始化程序中有条件地从数组中删除/删除元素。这种考虑违反了 Model 对象的责任角色。相反,它是 Controller 对象的工作。

但是你可以在模型类型中有一个访问点。比方说,您的 AlertsInbox 对象中有一个属性 messages。您可以拥有另一个具有另一个属性的访问点,比方说,limitedMessages 将是一个计算属性。

看下面的代码。我有意将类型的语义从 Class 更改为 Struct。但是您可以根据需要自由使用。

struct AlertsInbox: Codable {
let messages: [Message]

var limitedMessages: [Message] {
// here you will use the value of your limit
// if the limit exceeds the size of the array, whole array will be returned
return Array(messages.prefix(5))
}

struct Message: Codable {
let title: String
}
}

现在,当您需要实际消息的剥离版本时,您将像使用任何其他属性一样使用它。像 alertInbox.limitedMessages 而不是 messages 属性。


但如果你对以上不满意,想坚持你的计划,你也可以这样做。参见:

struct AlertsInbox: Codable {
let messages: [Message]

init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
let messages = try container.decode([Message].self, forKey: .messages)
// the idea of limiting the element numbers is same as the above
self.messages = Array(messages.prefix(5))
}

struct Message: Codable {
let title: String
}
}

关于ios - 在 Decodable 协议(protocol)中为模型数组设置容量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59098488/

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