Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save StewartLynch/94f5d2fe8eb19c7c418efc3731b05f72 to your computer and use it in GitHub Desktop.
Save StewartLynch/94f5d2fe8eb19c7c418efc3731b05f72 to your computer and use it in GitHub Desktop.
Is there a better way?
// 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()
@StewartLynch
Copy link
Author

StewartLynch commented Apr 14, 2022

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