I am attempting to modify Apple's code from the Landmarks tutorial to load JSON data from a remote URL. The url is a php script which returns plaintext JSON data.
Apple's code:
func loadLocalJSON<T: Decodable>(_ filename: String) -> 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) from main bundle:\n\(error)")
}
}
And my code as currently modified:
func loadRemoteJSON<T: Decodable>(_ urlString: String) -> T {
let data: Data
guard let url = URL(string: urlString) else {
fatalError("Invalid URL")
}
let request = URLRequest(url: url)
URLSession.shared.dataTask(with: request) { data, response, error in
guard let data = data else {
fatalError(error?.localizedDescription ?? "Unknown Error")
}
do {
let decoder = JSONDecoder()
return try decoder.decode(T.self, from: data) // <--ERROR HERE
} catch {
fatalError("Couldn't parse data from \(urlString)\n\(error)")
}
}
}
The error I am getting is Unexpected non-void return value in void function
I thought the function was supposed to be returning an instance of T. Where am I going wrong?