NEW: My new book Pro SwiftUI is out now – level up your SwiftUI skills today! >>

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.

1      

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

1      

Hacking with Swift is sponsored by Play

SPONSORED Play is the first native iOS design tool created for designers and engineers. You can install Play for iOS and iPad today and sign up to check out the Beta of our macOS app with SwiftUI code export. We're also hiring engineers!

Click to learn more about Play!

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.