Skip to content

Instantly share code, notes, and snippets.

@sanghapark
Created February 18, 2017 18:15
Show Gist options
  • Save sanghapark/ff52eac97863634d58cf746492c7bad4 to your computer and use it in GitHub Desktop.
Save sanghapark/ff52eac97863634d58cf746492c7bad4 to your computer and use it in GitHub Desktop.
Make sync function async
//: Playground - noun: a place where people can play
import UIKit
import PlaygroundSupport
PlaygroundPage.current.needsIndefiniteExecution = true
let userQueue = DispatchQueue.global(qos: .userInitiated)
let defaultQueue = DispatchQueue.global()
func slowAdd(_ input: (Int, Int)) -> Int {
sleep(2)
return input.0 + input.1
}
// TODO: Dispatch slowAdd to userQueue
func asyncSlowAdd(_ input: (Int, Int),
runQueue: DispatchQueue,
comletionQueue: DispatchQueue,
completion: @escaping (Int) ->() ) {
runQueue.async {
let result = slowAdd(input)
comletionQueue.async {
completion(result)
}
}
}
asyncSlowAdd((2,3), runQueue: userQueue, comletionQueue: defaultQueue) { result in
print(result)
}
print("after calling asyncSlowAdd")
sleep(3)
PlaygroundPage.current.finishExecution()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment