swift - swift中的异步延迟

标签 swift function asynchronous delay

如何在 swift 中获得异步延迟?

我有 3 个函数,假设函数 first()、second() 和 third() 是异步调用的。但是在 second() 函数中放置 10 秒的延迟后,第三个函数在 10 秒后被调用,而不是我只希望第二个函数中的代码在 10 秒后被调用而不是第三个函数。

提前致谢。

最佳答案

假设...

  • 您的所有函数都不包含任何异步调用,即每个函数中的所有指令都一个接一个地执行。
  • 函数之间没有依赖关系,可以按任意顺序执行。

...您可以使用 OperationQueue(以前是 Swift 2 中的 NSOperationQueue):

func first()  { print("First") }
func second() { print("Second") }
func third()  { print("Third") }

// Since we will block the queue while wait for all three functions to complete,
// dispatch it to a background queue. Don't block the main queue
DispatchQueue.global(qos: .background).async {
    let queue = OperationQueue()
    queue.addOperation(first)
    queue.addOperation(second)
    queue.addOperation(third)

    queue.waitUntilAllOperationsAreFinished()

    // Now all your functions are complete
}

请注意,即使按顺序添加功能,也无法确定其执行顺序。

关于swift - swift中的异步延迟,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39701790/

相关文章:

ios - PHAssetManager 在请求图像时忽略 targetSize?

Python:如何正确使用外部函数

javascript - 将私有(private)变量转换为公共(public)变量

javascript - underscore.js debounce 函数中的内部函数上下文

Python 异步和 CPU 密集型任务?

Android蓝牙socket非阻塞通信教程

swift - 有没有办法在新通知到达时删除已发送的通知?

swift - 如何在 Firebase 3 和 Swift 3 中检索一次数据(停止观察者)

ios - Swift 3 Xcode8 - 如何实例化按钮操作上的不同 View

javascript - 谷歌地图,多个物理地址,多个指针图标,始终显示同一个图标