Reputation: 807
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")
The function extracts the data form a JSON.
What is that 'parameter' type: T.Type = T.self
for? If I remove this parameter the code still works. So what do I need it for?
Upvotes: 1
Views: 612
Reputation: 15238
This parameter is just a helper to use three kind of declarations as below,
1) let model: Model = self.load("Countries")
2) let model = self.load("Countries", as: Model.self)
3) let model = self.load("Countries") as Model
You can remove it from the method signature if you want to use the first kind of declaration.
Upvotes: 5