func load<T: Decodable>(_ filename: String, as type: T.Type = T.self) -> T {
let data: Data
guard let file = Bundle.main.url(forResource: filename, withExtension: nil)
else {
fatalError("Couldn't find \(filename) in main bundle.")
}
do {
data = try Data(contentsOf: file)
} catch {
fatalError("Couldn't load \(filename) from main bundle:\n\(error)")
}
do {
let decoder = JSONDecoder()
return try decoder.decode(T.self, from: data)
} catch {
fatalError("Couldn't parse \(filename) as \(T.self):\n\(error)")
}
}
load("jsonFilePath")
该函数从JSON提取数据。
该“参数” type: T.Type = T.self
的作用是什么?如果我删除此参数,代码仍然有效。那我需要什么呢?
答案 0 :(得分:4)
此参数只是使用以下三种声明的助手,
1) let model: Model = self.load("Countries")
2) let model = self.load("Countries", as: Model.self)
3) let model = self.load("Countries") as Model
如果要使用第一种声明,可以将其从方法签名中删除。