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

Swift解码错误求助:期望数组却得到字典的问题排查

问题解决:Swift JSON解码类型不匹配错误

错误核心

你碰到的typeMismatch错误本质是:JSON的顶层结构是字典(Dictionary),但你的代码试图将其解码为数组(Array)类型,导致类型不匹配触发报错。

分步调试修正

1. 对齐JSON与结构体模型

假设你的JSON数据是类似这种顶层字典结构(如果实际结构不同,对应调整模型即可):

{
  "recyclingFacilities": [
    {
      "city": "广州",
      "name": "天河区电子垃圾回收中心"
    },
    {
      "city": "深圳",
      "name": "南山区环保处理站点"
    }
  ]
}

对应修正模型结构体,让它匹配JSON的层级:

// 单个回收设施的模型
struct RecyclingFacility: Codable {
    let city: String
    let name: String
}

// 匹配JSON顶层字典的结构体
struct UserData: Codable {
    let recyclingFacilities: [RecyclingFacility]
}

2. 修正DataLoader的解码逻辑

确保DataLoader里解码的是UserData类型,而非直接解码数组:

class DataLoader {
    var userData: UserData?
    
    init() {
        loadLocalData()
    }
    
    private func loadLocalData() {
        guard let fileURL = Bundle.main.url(forResource: "你的JSON文件名", withExtension: "json") else {
            print("JSON文件未找到")
            return
        }
        do {
            let rawData = try Data(contentsOf: fileURL)
            let decoder = JSONDecoder()
            // 解码为UserData类型,而非数组
            userData = try decoder.decode(UserData.self, from: rawData)
        } catch {
            print("解码失败:\(error)")
        }
    }
}

3. 在PhonesView中正确获取并筛选数据

现在可以正确取出数组并按城市筛选:

struct PhonesView: View {
    var filteredFacilities: [RecyclingFacility] = []
    
    init() {
        let loader = DataLoader()
        // 替换为你需要筛选的城市名称
        filteredFacilities = loader.userData?.recyclingFacilities.filter { $0.city == "广州" } ?? []
    }
    
    var body: some View {
        List(filteredFacilities, id: \.name) { facility in
            Text(facility.name)
        }
    }
}

额外检查项

  • 确认JSON文件名与代码中的名称一致,且已添加到项目Target中
  • 如果你的JSON顶层本身就是数组(比如直接是[{"city":"...", "name":"..."}]),则无需UserData结构体,直接让DataLoader解码为[RecyclingFacility].self即可

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.11 09:42:18