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

Swift 5 如何过滤JSON数组排除type=quiet项以初始化对应视图控制器

解决方案

你只需要在map映射前新增filter过滤逻辑,筛选掉type为quiet的元素即可,无需修改原有解码结构体和映射逻辑。

修改后的完整代码如下:

do {
  let nav = try JSONDecoder().decode([TestStruct].self, from: data)

  self.viewControllers = nav.filter {
      $0.type != "quiet"
  }.map { test -> UIViewController in
    let selected = UIImage(named: "Tab4_Large")!
    let normal = UIImage(named: "Tab4_Large")!
    let controller = storyboard!.instantiateViewController(withIdentifier: String(test.testid))
    controller.view.backgroundColor = UIColor.white
    controller.floatingTabItem = FloatingTabItem(selectedImage: selected, normalImage: normal)
    return controller
  }
} catch {
  // 可自行补充解码错误处理逻辑
  print("解码失败: \(error.localizedDescription)")
}

可选优化

如果后续还有多处需要判断TestStruct的类型,可以给结构体扩展计算属性提升代码可读性:

extension TestStruct {
    var isQuietType: Bool {
        type == "quiet"
    }
}

此时过滤代码可改写为:

nav.filter { !$0.isQuietType }

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.03 01:15:04