Get the Value of Variable Out of Closure Swift

get the value of variable out of closure swift

use completion for any asynchronous task in closure

func get(completion:(value: NSArray) -> Void){

// request part
let task = NSURLSession.sharedSession().dataTaskWithRequest(request) {
data, response, error in
// your serialization code

dispatch_async(dispatch_get_main_queue()) { [unowned self] in
self.values = array

// return value to completion
completion(value: array)

print ("error=\(self.values)")
self.tableView?.reloadData();
}
}
}

change the way you get the value in viewdidload

   get{(value) in
// finish NSURLSession task and everything should be done in this closure
self.values = value
print ("values=\(self.values)")
}

How do I access variables that are inside closures in Swift?

var dict: NSDictionary! // Declared in the main thread

The closure is then completed asynchronously so the main thread doesn't wait for it, so

println(dict)

is called before the closure has actually finished. If you want to complete another function using dict then you will need to call that function from within the closure, you can move it into the main thread if you like though, you would do this if you are going to be affecting UI.

var dict: NSDictionary!
NSURLConnection.sendAsynchronousRequest(request, queue: NSOperationQueue.mainQueue(), completionHandler: {(response, data, error) in
var jsonError: NSError?
let json = NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.MutableContainers, error: &jsonError) as? NSDictionary
dict = json
//dispatch_async(dispatch_get_main_queue()) { //uncomment for main thread
self.myFunction(dict!)
//} //uncomment for main thread
})

func myFunction(dictionary: NSDictionary) {
println(dictionary)
}

Swift variable declared outside closure is updated inside closure but when accessed outside closure it returns the default value?

Please use tabs to make your code easier readable.

Anyway geocoder.geocodeAddressString(address) is a method with a callback and in this callback method you have the placemark. Your return will not wait for that callback since it will take time to calculate the coordinates hence it returns 0.0 which you set at the start.


Edit: longer version since you asked in a comment:

CLGeocoder()'s function geocodeAddressString has in fact 2 parameters: the adress and a socalled callback. A callback is simply a method called when the task (in this case calcualting the placemark) finishes. Swift lets you write the callback in "swifty" syntax but actually it looks like

geocoder.geocodeAddressString(address, callAfterFinishGeocoding)

func callAfterFinishGeocoding(_ placemark: Placemark) {
// do stuff with placemark
}

as you can see we pass the geocode function another function to be called when done. The parameters of callAfterFinishGeocoding are defined in geocodeAddressString. It will look similar to this:

callback: @escaping (_ placeMark: Placemark) -> Void

This would mean the callback should be a function accepting a placemark and returning Void. Jump to the definition of the method see what kind of function it wants as parameter.

also read more here: https://stackoverflow.com/a/46245943/13087977

Getting data out of a closure in swift

Declare otherUsersCoord as a var outside the closure expression, rather than inside it. When it is assigned to within the closure, that change will be reflected in the variable outside the closure. This is known as “capturing” otherUsersCoord. Capturing external context is what makes closures more than just functions.

Beware though, you still need to wait for the closure to actually run before the variable will have the value you decide. It won’t be instantly synchronously available. Also, capturing external variables keeps them alive and can occasionally result in cyclic references and similar problems (this is why sometimes when you refer to a member variable or function you get a warning about “capturing self”).

how to get a value from an escaping closure and assign it to a variable and display in tableview

The problem was solved under my teacher's help.
The solution is creating an instance variable, then calling self.tableview.reload directly in the closure. In the tableView cellForRowAT, just loading the value from instance variable.

func searchAddress(_ address: String)
{
self.forwardGeocoding(address:address, completion: {(location) in
if let locationTo = location {
// calculate distance
self.donorDistance.append((self.mainDelegate.currLocation?.distance(from: locationTo) ?? 0))
print(self.mainDelegate.currLocation?.distance(from: locationTo) ?? 0)
if self.donorDistance.count == self.donors.count
{
self.tableview.reloadData()
}
} else {
// not found destination, show alert
print("cannot find address")
}
})
}

How do I set the return value of a closure function to a variable?

Try to set value of x variable inside of the closure:

loadData1(onCompletion: { (json) in
x = json
})

In your approach variable x initialized with a closure, that's why you received a warning.

Until closure will be executed, variable x have default value var x = [[String: String]]()
or remain unresolved if you did not provide default value along with declaration.

How to get the value of the variable that is assigned in a closure (Swift)

Your closure is async. What happens is that you go through all the function body before sendTwitterRequest assigns true to jsonAvailable, resulting in jsonAvailable being false. What you need to do is having a callback instead, providing the json status if you'd like (or the json itself as a nillable object).

EDIT: You could have something like this

func jsonAvailable(callback: ((_ isJsonAvailable: Bool) -> Void)) {
client.sendTwitterRequest(request) { (response, data, connectionError)-> Void in {
do {
let json = try JSONSerialization.jsonObject(with: data!, options: [])
print("json: \(json)")
callback(true)
} catch let jsonError as NSError {
print("json error: \(jsonError.localizedDescription)")
callback(false)
}
}
}

jsonAvailable(callback: { (_ isJsonAvailable: Bool) in
print(isJsonAvailable)
})

Accessing variable out completion block

By default, calling checkCreateTabPermission as:

checkCreateTabPermission { pass, employee, cancel in
// here you can use the `employee`
}

should make you able to access the returned employee. So, you could call the needed method inside the completion of checkCreateTabPermission:

checkCreateTabPermission { pass, employee, cancel in
myMethod(employee: employee)
}

Or if you want to access the employee outside of the completion, you could declare a variable (which is nil by default) to hold its value once it returned:

var myEmployee: Employee?

checkCreateTabPermission { [weak self] pass, employee, cancel in
self?.myEmployee = employee
}

// you could use `myEmployee` here, but you have to make sure its not nil,
// in other words, `checkCreateTabPermission` has been called and retrieved one.
if let myUnwrappedEmployee = myEmployee {
// use `myUnwrappedEmployee`...
}


Related Topics



Leave a reply



Submit