Last active
July 5, 2018 12:25
-
-
Save Alex-Ozun/179a4873b5afc14a2f9462c141ee9176 to your computer and use it in GitHub Desktop.
Convert async operation into sync getter
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
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