In my Code,I want to return some data in a fun after a network request.
func funcName()->String{
var data = "demo"
DataLoader.fetch { result in
if case .success(let fetchedData) = result {
data = fetchedData
} else {
data = "Fail"
}
}
return data
}
The DataLoader is used to get some data from API, the code just like:
struct DataLoader {
static func fetch(completion: @escaping (Result<String, Error>) -> Void) {
let url = URL(string: "URL LINK")!
let task = URLSession.shared.dataTask(with: url) { (data, response, error) in
guard error == nil else {
completion(.failure(error!))
return
}
completion(.success(data!))
}
task.resume()
}
}
But as you know data will always be "demo" because of escaping closure.
So how can I return the data after the network request complete without modify the function funcName's params?
If the parameters of the function are not modified.
I'm new in swift, and really at a loss.Thanks a lot if you could help me out!