0

After having trouble with calling an API and loading some data on the screen, I noticed that I need something to call my functions synchronously. I found out about DispatchGroup and decided to play around with it, but it doesn't work for me.

Take for example this small piece of code:

let myGroup = DispatchGroup()

for i in 0 ..< 5 {
    myGroup.enter()


    print("Finished request \(i)")
    myGroup.leave()
}

myGroup.notify(queue: .main) {
    print("Finished all requests.")
}

If I run this code in the Swift Playground, the 5 'Finished request i' messages get printed, but the 'Finished all requests' doesn't. This code is based on a Stack Overflow example, so I really don't know why it's not working. Thanks!

Jérémy
  • 405
  • 1
  • 4
  • 22

1 Answers1

1

In a playground, you need to specify that it runs "forever" in order to wait for asynchronous notifications etc.:

import PlaygroundSupport
... // your code
PlaygroundPage.current.needsIndefiniteExecution = true
Andreas Oetjen
  • 9,889
  • 1
  • 24
  • 34