TEAM LICENSES: Save money and learn new skills through a Hacking with Swift+ team license >>

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:

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.



Hacking with Swift is sponsored by Superwall.

SPONSORED Superwall lets you build & test paywalls without shipping updates. Run experiments, offer sales, segment users, update locked features and more at the click of button. Best part? It's FREE for up to 250 conversions / mo and the Superwall team builds out 100% custom paywalls – free of charge.

Learn More

Sponsor Hacking with Swift and reach the world's largest Swift community!

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.