0

I try to chain different functions. Go to the next function only when each one is completed.

I could find different ways to do that. For instance:

I tried and all that works well with two functions but also they became complicated when there are several functions and a lot of code.

I am looking for a solution that could help to keep the code clean and organized especially when there are several function.

For instance that keeps the code in the right order but it needs to add a way to go to the next func only when each one is completed.

override func viewDidLoad() {
    super.viewDidLoad()
    first()
}
func first () {
    print("first")
    second()
}
func second () {
    print("second")
    third()
}
func third () {
    print("third")
}
Nrc
  • 9,577
  • 17
  • 67
  • 114

1 Answers1

1

You can do this by DispatchQueueGroup

let queue = DispatchQueue(label: "com.company.app.queue", attributes: .concurrent)
let group = DispatchGroup()

group.enter()
queue.async {
    print("#1 started")
    Thread.sleep(forTimeInterval: 5)
    print("#1 finished")
    group.leave()
}

group.wait()

group.enter()
queue.async {
    print("#2 started")
    Thread.sleep(forTimeInterval: 2)
    print("#2 finished")
    group.leave()
}

group.wait()

queue.async {
    print("#3 finished")
}

How it works.

  • Simply Create a group.
  • Enter the group and start work for #1
  • Keep waiting for the group until #1 is done

A more and elaborate answer for you regarding this

https://stackoverflow.com/a/43022956/8475638

Ankur Lahiry
  • 2,253
  • 1
  • 15
  • 25
  • Thank you. Can you adapt to the simplest case possible, like the one I provided, please? This would help me understand better – Nrc May 08 '20 at 13:33
  • okay, think like that queue.async is like a method here(actually not a method). In every async, the block executes a long process by sleeping the thread. – Ankur Lahiry May 08 '20 at 13:44
  • Please explain your code. I put your code in a button and the two let outside. I see what it does. But I am not sure those two let do? – Nrc May 08 '20 at 13:50
  • Please follow through the link I have given first. Learn Dispatch Queue from the doc https://developer.apple.com/documentation/dispatch/dispatchqueue Then paste my code in the playground and run code. Remove and wait and re-run what happening there. You will surely understand what is happening. :) After that, you will get my answer actually. – Ankur Lahiry May 08 '20 at 13:53