Skip to content

Instantly share code, notes, and snippets.

@kiruto
Created December 21, 2018 04:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kiruto/72d12d6614276f283a3c12ae5d289fc7 to your computer and use it in GitHub Desktop.
Save kiruto/72d12d6614276f283a3c12ae5d289fc7 to your computer and use it in GitHub Desktop.
swift 4 async / await
//
// Created by Kiruto on 2018-12-21.
//
import Foundation
struct Await<T> {
// private
fileprivate let group: DispatchGroup
fileprivate let getResult: () -> T
// public
func await() -> T { return getResult() }
}
func async<T>(_ queue: DispatchQueue, block: @escaping () -> T) -> Await<T> {
let group = DispatchGroup()
var result: T?
queue.async(group:group) {
trace("start")
result = block()
trace("end")
}
queue.suspend()
return Await(group: group, getResult: {
group.wait()
return result!
})
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment