How to change a variable from a nested function?

When a variable changes inside a region of a nested function, it does not change as soon as the region remains. In my code example, when I set the xmlString variable to be equal to the response, it correctly receives the response. But then it returns an empty string.
func getXmlString(url: String) -> String { var xmlString: String = "" Alamofire.request(.GET, url) .validate() .responseString { response in xmlString = response.result.value! } return xmlString }
I know that there is only a tiny thing that I am missing, and any help in understanding my situation will help me. Thanks

+4
source share
1 answer

Alamofire- acsynchonus. This is why your xmlString is empty. You must wait until you receive a response from Alamofire.

 func getXmlString(url: String, completion: (xmlString: String) -> ()) {
            var xmlString: String = ""
            Alamofire.request(.GET, url)
                .validate()
                .responseString { response in
                    xmlString = response.result.value!

                 completion(xmlString)
             }
}

And use it

getXmlString(url: String){ xmlString in

//do something with your String
}
+1
source

All Articles