I'm trying to call a function from view using SwiftUI. This view receive an String parameter from view that is calling it.
struct BookList: View {
var name: String
var body: some View {
let data: () = getData(from: self.name)
...
}
}
The function get data is consuming a rest service and getting some data.
func getData(from url: String){
let task = URLSession.shared.dataTask(with: URL(string: url)!, completionHandler: { data, response, error in
guard let data = data, error == nil else {
print("Something went wrong")
return
}
//Have data
var result: Response?
do {
result = try JSONDecoder().decode(Response.self, from: data)
} catch {
print("failed to convert \(error.localizedDescription)")
}
guard let json = result else{
return
}
print("Page: \(json.page)")
print("Books: \(json.books.first)")
})
task.resume()
}
struct Response: Codable {
var error: String
var total: String
var page: String
var books: [MyBook]
}
The problem is that I don't know how to call this function when view start. In this sample I'm getting the error:
"Function declares an opaque return type, but has no return statements in its body from which to infer an underlying type"
How can I fix it?