Skip to content

Instantly share code, notes, and snippets.

@Alex-Ozun
Last active July 5, 2018 12:25
Show Gist options
  • Save Alex-Ozun/179a4873b5afc14a2f9462c141ee9176 to your computer and use it in GitHub Desktop.
Save Alex-Ozun/179a4873b5afc14a2f9462c141ee9176 to your computer and use it in GitHub Desktop.
Convert async operation into sync getter
func syncGetter<T>(block: (@escaping (T?) -> Void) -> Void) -> T? {
let dispatchGroup = DispatchGroup()
var returnValue: T?
dispatchGroup.enter()
block() { value in
returnValue = value
dispatchGroup.leave()
}
dispatchGroup.wait()
return returnValue
}
///EXAMPLE
let downloadImage = { (completion: @escaping (UIImage?) -> Void) in
DispatchQueue.global().async {
let data = try! Data(contentsOf: URL.init(string: "https://upload.wikimedia.org/wikipedia/commons/6/69/NASA-HS201427a-HubbleUltraDeepField2014-20140603.jpg")!)
completion(UIImage(data: data))
}
}
let image: UIImage? = syncGetter(block: downloadImage)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment