You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Swift5 如何过滤匹配两个字符串的JSON数组并转为对象数组

问题1:多状态匹配过滤实现

你原有用||拼接两个判断条件的写法已经可以实现需求,如果后续需要扩展更多可选状态,更易维护的写法是把允许的状态存入集合,用contains判断:

let allowedStatus: Set = [self.st_pending, self.st_driver_rejected]
self.arrListPending = self.arrListAll.filter { 
    allowedStatus.contains($0["status"].stringValue) 
}
问题2:SwiftyJSON字典数组转对象数组实现

你需要先定义和JSON字段匹配的模型结构体,再通过JSONDecoder做解码即可,示例代码如下:

  1. 定义模型结构
// 商品明细模型
struct ProductItem: Codable {
    let itemName: String
    // 按需补充其他商品字段:比如价格、数量等
    enum CodingKeys: String, CodingKey {
        case itemName = "item_name" // 匹配JSON的下划线命名
    }
}

// 订单模型
struct OrderModel: Codable {
    let status: String
    let itemData: [ProductItem]
    // 按需补充其他订单字段:比如订单号、时间等
    enum CodingKeys: String, CodingKey {
        case status
        case itemData = "item_data" // 匹配JSON的下划线命名
    }
}
  1. 把接口返回的JSON直接解码为模型数组
do {
    // 从SwiftyJSON对象里取原始数据
    let jsonData = try swiftyJsonVar["result"].rawData()
    // 解码为订单模型数组
    self.arrListAll = try JSONDecoder().decode([OrderModel].self, from: jsonData)
} catch {
    print("模型解码失败: \(error.localizedDescription)")
}
  1. 转换完成后即可直接通过属性取值,不需要再走字典下标
let order = arrListPending[indexPath.row]
let productNames = order.itemData.map { $0.itemName }

这种写法编译时会做属性校验,不会因为写错字段key出现运行时崩溃,代码可读性和可维护性更高。

内容的提问来源于stack exchange,提问作者bircastri

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.03 11:06:05