Why does the print("2")
part never get called in the following code?
I'd think that the inner main.async
would push the block into the main loop's queue,
and then RunLoop.run
would execute it, but apparently that isn't what happens.
(It prints 1
, run
, run
, run
, etc.)
Also, if I remove the outer main.async
, and just directly run the code in that block
(still on the main queue, in viewDidLoad
of a new single-view app),
then the inner main.async
block does get executed (prints 1
, run
, 2
).
Why does this change make such a difference?
var x = -1
DispatchQueue.main.async { // comment out this line for question #2
print("1")
x = 1
DispatchQueue.main.async {
print("2")
x = 2
}
while x == 1 {
print("run")
RunLoop.main.run(mode: .default, before: Date() + 1)
}
} // comment out this line for question #2