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
相关产品推荐
相关产品推荐

