S. Doe
S. Doe

Reputation: 163

Wait for asynchronous block before continuing

I have a function lets call it "a" that runs some code and then returns a string "x" is updated in an asynchronous code block and then returned.

How would I go about making the program wait to return x until after the asynchronous code runs?

func a() -> String {

    //code
    //code
    var x: String
    async block {

    x = "test"
    }
    return x
}

Upvotes: 7

Views: 6396

Answers (2)

ebby94
ebby94

Reputation: 3152

Like everyone pointed out you can use a completion handler(closure) to perform the operation. But you can also wait for the asynchronous call to be completed using DispatchSemaphore. The semaphore obtains a lock when it makes wait call and it's released when it's signaled from the asynchronous block.

func a() -> String {
    var x = ""
    let semaphore = DispatchSemaphore(value: 0)
    DispatchQueue.main.async {
        x = "test"
        semaphore.signal()
    }
    semaphore.wait()
    return x
}

Upvotes: 13

kathayatnk
kathayatnk

Reputation: 1015

You can use completion closure for this

func a(completion: @escaping (_ value:String)->()) {
    var x: String = ""
    async block {
      x = "test"
      completion(x) //when x has new value
    }
}

//Call like this (value will be executed when the completion block is returned

a { (value) in
     print(value)
  }

Upvotes: 2

Related Questions