Harry Day
Harry Day

Reputation: 408

Swift Updating variable inside of data task

I am writing a Network class for my app. One function carries out the actual request to the API I am using

as part of this function I am using a URLSession.shard.dataTask().

var decodedResponse = SongLinkAPIResponse()
        
let task = session.dataTask(with: url) { data, response, error in
            
            let result = data.map(Result.success) ?? Result.failure(DataLoaderError.network(error!))
            let handlerResult = handler(result)
//          This handler just decodes the downloaded JSON into a SongLinkAPIResponse struct. 
//          This works fine and I can see this is working
            


            DispatchQueue.main.async {
                switch handlerResult {
                    case .success(let response):
//                      When I run this code in a playground I can see that this line shows as working in the sidebar

                        decodedResponse = response
                    case .failure(let error):
                        print(error)
                }
            }
        }
        
task.resume()

//However when returning this variable it just has the empty default configuration of the struct

return decodedResponse

Any ideas on why the variable is not updating? Thanks in advance

Upvotes: 0

Views: 785

Answers (1)

pawello2222
pawello2222

Reputation: 54486

session.dataTask is asynchronous. It will execute some time in the future.

Your code will execute in the following order.

// 1
var decodedResponse = SongLinkAPIResponse()

// 2        
let task = session.dataTask(with: url) { data, response, error in
            // 4
            ...
        }
        
task.resume()

// 3
return decodedResponse

Here are some possible explanations/solutions:

Upvotes: 1

Related Questions