-
-
Save OctoberHammer/2298e179a7f2fd89e0e9e8784e565147 to your computer and use it in GitHub Desktop.
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
import Foundation | |
import PlaygroundSupport | |
PlaygroundPage.current.needsIndefiniteExecution = true | |
func async<T>(_ executable: @escaping @autoclosure () -> T, _ priority: DispatchQoS.QoSClass = DispatchQoS.QoSClass.default, completion: @escaping (T) -> Void) { | |
DispatchQueue.global(qos: priority).async { | |
let result = executable() | |
DispatchQueue.main.async { | |
completion(result) | |
} | |
} | |
} | |
func asyncWithError<T>(_ executable: @escaping @autoclosure () throws -> T, _ priority: DispatchQoS.QoSClass = DispatchQoS.QoSClass.default, completion: @escaping (T?, Error?) -> Void) { | |
DispatchQueue.global(qos: priority).async { | |
var result: T? = nil | |
var error: Error? = nil | |
do { | |
result = try executable() | |
} | |
catch let caughtError { | |
error = caughtError | |
} | |
DispatchQueue.main.async { | |
completion(result, error) | |
} | |
} | |
} | |
class TestExecutor { | |
func perform(_ input: String) -> String { | |
return input + " Performed" | |
} | |
enum Error: String, Swift.Error, LocalizedError { | |
case Empty | |
var errorDescription: String? { | |
return self.rawValue | |
} | |
} | |
func throwingPerform(_ input: String) throws -> String { | |
if input.isEmpty { | |
throw Error.Empty | |
} | |
return self.perform(input) | |
} | |
} | |
let executor = TestExecutor() | |
let syncResult = executor.perform("Hi") | |
async(executor.perform("Async")) { result in | |
print(result) | |
} | |
asyncWithError(try executor.throwingPerform("")) { result, error in | |
print("result: ", result ?? "no result", ", error: ", error?.localizedDescription ?? "no error") | |
PlaygroundPage.current.finishExecution() | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment