如何在 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/