【问题标题】:Asynchronous Delay in swiftswift中的异步延迟
【发布时间】:2023-03-31 00:38:01
【问题描述】:

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

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

提前致谢。

【问题讨论】:

  • 贴一些你试过的代码
  • func second () { delay(seconds: 10) { print("调用的第二个函数") }}
  • 请教我如何使用回调函数?我是新来的 swift
  • 我建议您搜索有关回调的答案的问题或询问有关回调的新问题。

标签: swift function asynchronous delay


【解决方案1】:

假设...

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

...你可以使用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
}

请注意,即使按顺序添加函数,也无法确定它们的执行顺序。

【讨论】:

    猜你喜欢
    • 2016-02-02
    • 1970-01-01
    • 2019-03-13
    • 2018-08-01
    • 2018-06-13
    • 2018-09-26
    • 2019-01-15
    • 2020-09-02
    • 1970-01-01
    相关资源
    最近更新 更多