Created
April 14, 2022 05:24
-
-
Save StewartLynch/94f5d2fe8eb19c7c418efc3731b05f72 to your computer and use it in GitHub Desktop.
Is there a better way?
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// is there a better way to do this? | |
// I want to be able to execute something after all of the items have printed | |
func doIt() { | |
let numItems = 3 | |
for item in 0...numItems { | |
DispatchQueue.main.asyncAfter(deadline: .now() + (Double(item) * 1)) { | |
print(item) | |
} | |
} | |
DispatchQueue.main.asyncAfter(deadline: .now() + Double(numItems + 1)) { | |
print("Done") | |
} | |
} | |
doIt() |
Thanks. This was above and beyond and more than I actually needed. The solution for my example is just
func doIt() async {
let numItems = 3
for item in 0...numItems {
try? await Task.sleep(seconds: 1)
print(item)
}
try? await Task.sleep(seconds: 1 )
await completion()
}
func completion() async {
print("Done")
}
Task {
await doIt()
}
extension Task where Success == Never, Failure == Never {
static func sleep(seconds: Double) async throws {
let duration = UInt64(seconds * 1_000_000_000)
try await Task.sleep(nanoseconds: duration)
}
}
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Hey Stewart try this