Anirudha Mahale
Anirudha Mahale

Reputation: 2596

Asynchronous Delay in swift

How can I get async delay in swift?

I have 3 functions say suppose function first(), second() and third() which are called asynchronously. But after putting delay of 10sec in second() function, the third function is called after 10sec rather than I just want the code inside the function second to be called after 10sec and not the third function.

Thanks in advance.

Upvotes: 0

Views: 375

Answers (1)

Code Different
Code Different

Reputation: 93161

Assume that...

  • All your functions do not contain any async call, i.e. all instructions in each function follow one another.
  • There's no dependancy between the functions and they can be executed in any order.

... you can use OperationQueue (formerly NSOperationQueue in Swift 2):

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
}

Note that even though the functions are added in order, their execution order cannot be determined.

Upvotes: 1

Related Questions