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      

BUILD THE ULTIMATE PORTFOLIO APP Most Swift tutorials help you solve one specific problem, but in my Ultimate Portfolio App series I show you how to get all the best practices into a single app: architecture, testing, performance, accessibility, localization, project organization, and so much more, all while building a SwiftUI app that works on iOS, macOS and watchOS.

Get it on Hacking with Swift+

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.