0

I want to get value for variable guestname from closure and guestname is defined as global virable then pass this value to other class that use it. But the problem is that when i print out the guestname outside the closure it's empty but inside i see the actual value. So when i passed guestname to other class it pass nil caused problem. What is correct way to assign the value to guestname and get this value out of closure? Thanks

queryUserID?.getFirstObjectInBackground(block: { (object, error) in
                if error == nil {
                guestname = object!.value(forKey: "username") as! String

                }
            })
rmaddy
  • 314,917
  • 42
  • 532
  • 579
alvin123
  • 79
  • 2
  • 8

2 Answers2

1

The problem is your closure performs an async task, so obviously you will not get the value of your "guestname" variable outside. This is where completion blocks come into play. You can write a completion block for your closure and return the fetched result.

Look at this stackoverflow post which explains your scenario and teaches you how to write a completion block for your closure. I hope this helps.

Rizwan Ahmed
  • 919
  • 13
  • 19
1

I think you must pass data from closure itself like all completion blocks do

queryUserID?.getFirstObjectInBackground() { [weak CLASS] (object, error) in
    if let unwrappedObject = object as? String,
        error == nil {
            guestname = unwrappedObject.value(forKey: "username")
            CLASS?.passData(guestname)
    }
}
tereks
  • 1,256
  • 9
  • 15