Littleor
Littleor

Reputation: 33

How to use a escaping closure in a func to return some data?

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!

Upvotes: 0

Views: 356

Answers (1)

Frankenstein
Frankenstein

Reputation: 16341

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)
}

Upvotes: 2

Related Questions