The for loop doesn't wait, it is executed in the main thread. DispatchQueue.main.asyncAfter
doesn't block the main thread, all it does is queue a block of code to be executed after certain time. Queuing the printing of i
is done at almost the same time, maybe spaced in time by a few microseconds if not nanoseconds.
Instead of trying to block the main thread, you could use the Timer
API :
//In a playground
var timer: Timer? = nil
var counter = 0
timer = Timer.scheduledTimer(withTimeInterval: 1.0, repeats: true) { _ in
print("\(counter)\t\(Date())")
if counter == 10 {
timer?.invalidate()
}
counter += 1
}
timer?.fire()
Which would print for example:
0 2019-08-19 20:19:36 +0000
1 2019-08-19 20:19:37 +0000
2 2019-08-19 20:19:38 +0000
3 2019-08-19 20:19:39 +0000
4 2019-08-19 20:19:40 +0000
5 2019-08-19 20:19:41 +0000
6 2019-08-19 20:19:42 +0000
7 2019-08-19 20:19:43 +0000
8 2019-08-19 20:19:44 +0000
9 2019-08-19 20:19:45 +0000
10 2019-08-19 20:19:46 +0000