Created
December 21, 2018 04:20
-
-
Save kiruto/72d12d6614276f283a3c12ae5d289fc7 to your computer and use it in GitHub Desktop.
swift 4 async / await
This file contains 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
// | |
// 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