SwiftUI - Returning a variable from a function

SwiftUI beginner here. I am trying to set the value of a variable by calling a method inside a function. Although the method is evaluating correctly, I am not able to return the value of the variable. Please see my code:

Code Block func fetchTRCfunc() -> String {
    let headers: HTTPHeaders = [
        "refreshtoken": refreshToken
    ]
    let sessionManager = Alamofire.Session.default
    let request = sessionManager.request(url, method: .post, headers: headers)
    var ttrr: String = "default"
    request.responseJSON { (response) in
        switch response.result {
        case .success( _):
            let json = JSON(response.value!) //SwiftyJSON
            let tr = json[0]["TRCRate"].double!
            ttrr = String(tr)
            print("ttrr in request: \(ttrr)")
        case .failure(let error):
            print("API Manager Error: \(error)")
        }
    }
    //5. Return the ready-to-use data
    print("ttrr before return: \(ttrr)")
    return ttrr
}


And here is the print output:
ttrr bfore return: default
ttrr in request: 0.18


Could someone kindly point to what I am doing wrong? Thanks in advance.



Sorry, the first line did not come through in my original post. Here is the code again:


Code Block
func fetchTRCfunc() -> String {




request.responseJSON executes asynchronously, so your method is returning, before the request's closure has finished (specifically, before it has set the new value for ttrr).

So the method will always return ttrr = "default"

You need to action the new value of ttrr within the request's closure (after you set ttrr = String(tr).
I have several of these types of calls within my app. It's going to look something like this:

Code Block
private func findSomething(completion: @escaping (Object?) -> Void) {
loadJsonData(url: URL!) { (data, response, error) in
if (error != nil) {
let myObject = Object(<params>) - Or JSON decode here
completion(myObject)
}
else { completion(nil) }
}     
}


Notice there is no return type, only a completion function that you can name whatever you like. Then just call it:

Code Block
findSomething() { (object) in
if (object != nil) {
print(object)
} else {
print("Did not find anything")
}
}


SwiftUI - Returning a variable from a function
 
 
Q