2016-09-26 128 views
0

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

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

在此先感谢。

+0

发布一些代码,你tryed – Ragul

+0

FUNC第二(){延迟(秒:10){ 打印( “所谓的第二功能”) }} –

+0

请你能告诉我如何使用回调?我是swift新手 –

回答

1

假设......

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

...您可以使用OperationQueue(斯威夫特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 
} 

注意,他们的执行顺序无法确定。