Does forEach Run Asynchronously?

My app got a memory issue. The code was like

func foo() {
  var bar = [String:[String]]()
  ....
  #if DEBUG
  bar.keys.sorted().forEach { key in
    print(key, "\t", bar[key]!)
  }
  #endif

Since there was a memory issue, I decided to move the bar to be a class instance variable and free it every time.

class some {
  lazy private var bar = [String:[String]]()

  func foo() {
    defer {
      bar..removeAll(keepingCapacity: true)
    }  
    ....
    #if DEBUG
    bar.keys.sorted().forEach { key in
      print(key, "\t", bar[key]!)
    }
    #endif

However, the second code crashed immediately after the app ran on print(key, "\t", bar[key]!).

The reason of the crash was because the bar was already empty, which was not expected by me. So the forEach must be ran asyncronously. And the removeAll ran first.

I could fix the app by changing forEach to for-loop, but I wanted to make sure my thinking was right or not.

Have you tried placing a breakpoint inside the defer and inside the forEach and seeing which gets triggered first? I would be very surprised if forEach ran async.

It turned out more complex than my think. The issue was not on the forEach, as for loop also crashed.

The issue was because I used 2 Tasks in my function, so the app was not run in the order as I wanted. As I didn't know Task was async.

I changed the code and tried to use less and simple Tasks. Everything went fine now.