Created
February 18, 2017 18:15
-
-
Save sanghapark/ff52eac97863634d58cf746492c7bad4 to your computer and use it in GitHub Desktop.
Make sync function async
This file contains hidden or 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
//: 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