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

Codable解码出错时如何获取codingPath?Swift代码报错求助

Swift解码错误中正确获取codingPath的方法

你遇到的报错是因为DecodingError没有直接的context属性——它是一个枚举,不同的解码错误场景对应不同的case,只有每个case内部才包含带有codingPath的上下文信息,直接访问decodingError.context会让编译器无法确定表达式类型,因此抛出“Type of expression is ambiguous without more context”错误。

正确获取codingPath的写法

通过switch语句匹配DecodingError的所有枚举case,在每个case中提取对应的上下文信息,从而拿到codingPath:

do {
    guard let firstValue = result.values.first else {
        completion?(nil, NSError(domain: "MyDomain", code: 1, userInfo: [NSLocalizedDescriptionKey: "No first value found"]))
        return
    }
    let jsonData = try JSONSerialization.data(withJSONObject: firstValue, options: [])
    let decoder = JSONDecoder()
    let decodedObject = try decoder.decode(T.self, from: jsonData)
    completion?(decodedObject, nil)
} catch let decodingError as DecodingError {
    print("Failed to decode JSON: \(decodingError)")
    // 匹配所有DecodingError枚举case,提取codingPath
    switch decodingError {
    case .keyNotFound(let key, let context):
        print("Key '\(key)' not found. Coding path: \(context.codingPath)")
    case .valueNotFound(let type, let context):
        print("Value of type '\(type)' not found. Coding path: \(context.codingPath)")
    case .typeMismatch(let type, let context):
        print("Type mismatch for '\(type)'. Coding path: \(context.codingPath)")
    case .dataCorrupted(let context):
        print("Data corrupted. Coding path: \(context.codingPath)")
    @unknown default:
        print("Unknown decoding error occurred.")
    }
} catch let error {
    print("An error occurred: \(error)")
}

各case说明

  • .keyNotFound: 找不到模型中声明的某个Key时触发,可获取缺失的Key和编码路径
  • .valueNotFound: 指定位置缺少预期类型的值时触发,可获取预期的类型和编码路径
  • .typeMismatch: JSON值的类型与模型声明的类型不匹配时触发,可获取不匹配的类型和编码路径
  • .dataCorrupted: JSON数据格式损坏无法解析时触发,可获取编码路径
  • @unknown default: 兼容未来Swift版本新增的DecodingErrorcase,避免编译报错

内容的提问来源于stack exchange,提问作者János

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.31 22:31:15