WWDC23 SALE: Save 50% on all my Swift books and bundles! >>

Confused About DispatchQueue.main.asyncAfter(deadline: .now() + Double(i))

Forums > Books

Hi Everyone,

I'm working through the text of Hacking with iOS: SwiftUI Edition but am confused about this technique (for easier reference it's also posted on this page: https://www.hackingwithswift.com/books/ios-swiftui/manually-publishing-observableobject-changes)

In the technique project this line of code is inside a for / in loop like this:

init() { for i in 1...10 { DispatchQueue.main.asyncAfter(deadline: .now() + Double(i)) { self.value += 1 } } }

If the value of i is incremented by 1 each time the loop runs, why isn't the "dispatch" happening later and later each time. In other words, I was expecting the code to run 1 second later, then after a two second delay, then after a three second delay, etc. all the way to the final pass happening after a ten second delay when i ultimately becomes 10.

I hope that made sense. I appreciate any insight.


Hi @jimdube,

The reason is that to run the for loop take no time at all (milliseconds), however the closure wait in the background(async) for 1...10 seconds to complete.

Hope that clear.



Save 50% in my WWDC23 sale.

SAVE 50% To celebrate WWDC23, all our books and bundles are half price, so you can take your Swift knowledge further without spending big! Get the Swift Power Pack to build your iOS career faster, get the Swift Platform Pack to builds apps for macOS, watchOS, and beyond, or get the Swift Plus Pack to learn advanced design patterns, testing skills, and more.

Save 50% on all our books and bundles!

Archived topic

This topic has been closed due to inactivity, so you can't reply. Please create a new topic if you need to.

All interactions here are governed by our code of conduct.

Unknown user

You are not logged in

Log in or create account

Link copied to your pasteboard.