static let videos: [Video] = Bundle.main.decode("videos.json")报错Value of type 'Bundle' has no member 'decode'
时间: 2024-03-23 17:40:44 浏览: 9
这个错误提示是因为 Bundle 类型没有自带的 decode 方法。你可以通过在你的项目中创建一个扩展来添加一个自定义的 decode 方法,如下所示:
```
extension Bundle {
func decode<T: Decodable>(_ type: T.Type, from file: String) -> T {
guard let url = self.url(forResource: file, withExtension: nil) else {
fatalError("Failed to locate \(file) in app bundle.")
}
guard let data = try? Data(contentsOf: url) else {
fatalError("Failed to load \(file) from app bundle.")
}
let decoder = JSONDecoder()
guard let result = try? decoder.decode(T.self, from: data) else {
fatalError("Failed to decode \(file) from app bundle.")
}
return result
}
}
```
这个扩展将为 Bundle 类型添加一个 decode 方法,它将从指定的文件中加载 JSON 数据,并将其解码为指定的类型。你可以使用它来加载你的 `videos.json` 文件,就像这样:
```
let videos: [Video] = Bundle.main.decode("videos.json")
```
这个调用会返回一个 `[Video]` 类型的数组,它包含了从 `videos.json` 文件中解码出来的数据。