UPGRADE YOUR SKILLS: Learn advanced Swift and SwiftUI on Hacking with Swift+! >>

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.

3      

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.

Nigel

3      

Hacking with Swift is sponsored by Essential Developer

SPONSORED Join a FREE crash course for mid/senior iOS devs who want to achieve an expert level of technical and practical skills – it’s the fast track to being a complete senior developer! Hurry up because it'll be available only until April 28th.

Click to save your free spot now

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.