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

Swift使用PropertyListDecoder解码plist文件报错如何解决?

问题原因及修复方案

错误原因梳理

  • 第一个报错Expected to decode Dictionary<String, Any> but found an array instead:你的plist根节点是数组类型,但最初尝试解码的ToolsItem是结构体(对应字典类型),类型不匹配导致解码失败。
  • 第二个报错No value associated with key "tools":改为解码[ToolsItem]后,数组内的每个元素字典里不存在tools这个key;同时你的Items结构体属性名和plist里的key不匹配:plist里对应物品名称的key是item,但模型里写的是itemName,也会导致解码失败。

修复步骤

步骤1:修正数据模型

删掉冗余的ToolsItem结构体,同时修正Items的属性名和plist字段匹配:

struct Tools: Codable {
    let imageIcon: String
    let toolsName: String
    var items: [Items]
}

struct Items: Codable {
    // 属性名和plist的key保持一致
    let item: String
    let borrower: String
}

如果不想修改属性名,也可以用CodingKeys做字段映射:

struct Items: Codable {
    let itemName: String
    let borrower: String
    
    enum CodingKeys: String, CodingKey {
        case itemName = "item"
        case borrower
    }
}

步骤2:修正解码逻辑

直接解码[Tools].self类型即可:

class DataManager {
    
    static let shared = DataManager()
    
    func fetch() {
        guard let path = Bundle.main.path(forResource: "ToolsData", ofType: "plist") else { return }
        let url = URL(fileURLWithPath: path)
        
        do {
            let data = try Data(contentsOf: url)
            // 直接解码为Tools数组
            let toolsList = try PropertyListDecoder().decode([Tools].self, from: data)
            print(toolsList)
        } catch {
            print(error)
        }
        
    }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.07 04:39:03