在 Decodable 协议中为模型数组设置容量

Set capacity to array of model in Decodable protocol

即使 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 的初始值设定项中有条件地 strip/drop 从数组中取出元素。这种考虑违背了 Model 对象的责任角色。相反,它是控制器对象的工作。

但是你可以在模型类型中有一个访问点。比方说,您的 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
    }
}