D
D
driverx182021-03-13 19:52:57
Swift
driverx18, 2021-03-13 19:52:57

How to work with the data received in the closure after exiting it?

Here is a piece of code below

func getData() {
let url = URL("...url...")!

        let task = URLSession.shared.dataTask(with: url) {(data, response, error) in
            guard let data = data else { return }
         
            
            let root = try? JSONDecoder().decode(Root.self, from: data)
          
            print(root?.results[0])
        }.resume()

}


I need to get after the closure the data that I parsed to do in the getData return function. But this stubbornly fails, because, as I know, in swift it is impossible to return data in closures
. But what if I still need to return this data?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
B
briahas, 2021-03-13
@briahas

1) use delegates
2) use completions that were passed to the getData method and then used inside the closure:

func getData(completionHandler: (data: MyData?) -> Void) {
    let url = URL("...url...")!

    let task = URLSession.shared.dataTask(with: url) {(data, response, error) in
        guard let data = data else { return }
            
        let root = try? JSONDecoder().decode(Root.self, from: data)
          
        print(root?.results[0])
        completionHandler(root?.results[0])
    }.resume()
}

type of such. Well, that's a rough approach. It would also be nice to have an alarm there - the data was received and parsed successfully or "a ship!!!".

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question