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

Swift解码本地JSON文件遇Xcode报错,寻求解决方案

解决Xcode中Data(contentsOf: url)的类型不匹配Bug

错误出在Data(contentsOf: url)代码行,报错信息:

Argument type 'URL' does not conform to expected type 'Decoder'

这是一个Xcode的恼人Bug,在其他项目中不会出现,但已有可行方案解决。

相关代码与文件

本地JSON文件(含ISO2代码的国家列表)

[{"name": "Afghanistan", "code": "AF"},
{"name": "Åland Islands", "code": "AX"},
{"name": "Albania", "code": "AL"}]

模型结构体

struct CountryModel : Codable, Identifiable {
    var id = UUID()
    var name: String
    var code: String
}

出错的解码尝试代码

guard let url = self.url(forResource: file, withExtension: nil) else {
    fatalError("Failed to locate \(file) in the bundle.")
}

guard let data = try? Data(contentsOf: url) else {
    fatalError("Failed to load \(file) from the bundle.")
}

let decoder = JSONDecoder()

guard let loaded = try? decoder.decode([CountryModel].self, from: data) else {
    fatalError("Failed to decode.")
}

可行解决方法

  • 显式指定Foundation的Data:将Data(contentsOf: url)改为Foundation.Data(contentsOf: url),避免项目中自定义的同名类型导致编译器识别错误
  • 检查命名冲突:排查项目中是否存在自定义的Data结构体/类,如有则重命名该自定义类型
  • 清理Xcode缓存并重启:使用快捷键Cmd+Shift+K清理Build Folder,然后关闭并重新打开Xcode

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.28 17:53:32