0

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!

Littleor
  • 33
  • 5
  • 1
    "But as you know data will always be "demo" because escaping closure".. data will be demo becuase it will return the value before the network request has completed and the closure called. – Scriptable Jul 08 '20 at 09:58
  • Does this answer your question? [Returning data from async call in Swift function](https://stackoverflow.com/questions/25203556/returning-data-from-async-call-in-swift-function) – Joakim Danielson Jul 08 '20 at 10:48

1 Answers1

2

You have to modify the funcName also to completion closure, instead of return.

func funcName(completion: @escaping (String) -> Void) {
    var data = "demo"
    DataLoader.fetch { result in
        if case .success(let fetchedData) = result {
            data = fetchedData
        } else {
            data = "Fail"
        }
        completion(data)
    }
}

And usage:

funcName { name in
    print(name)
}
Frankenstein
  • 15,732
  • 4
  • 22
  • 47