如何使一个代码仅在另一个代码在 Swift 中完成后运行

Shi*_*ira 3 concurrency synchronization ios swift

我是异步和同步机制的新手。在我的代码中,我必须在另一行完成后才执行另一行代码。它看起来像这样:

    func something(){

    let workerQueue = DispatchQueue.global(qos: .userInitiated)
            workerQueue.async{
         let info = getInfoFromTheWeb()//I need the info value in order to perform the next line
         saveToDB(info: info)

      DispatchQueue.main.async {
       //update a label text in the ui after getting and saving that info
      }

    }
}
Run Code Online (Sandbox Code Playgroud)

请你的专业意见..

Usm*_*ved 5

你的应该DispatchGroup。通过使用DispatchGroup一个函数/一行代码将等待另一个函数完成执行。

例如

let myGroup = DispatchGroup()
   myGroup.enter()
   let info = getInfoFromTheWeb()
Run Code Online (Sandbox Code Playgroud)

当你info从简单的电话中得到

myGroup.leave()
Run Code Online (Sandbox Code Playgroud)

当您的调用leave()函数下面的代码将被执行时

myGroup.notify(queue: DispatchQueue.main) {

            saveToDB(info: info)
           /// Update UI elements
        }
Run Code Online (Sandbox Code Playgroud)