Skip to content

Instantly share code, notes, and snippets.

@OctoberHammer
Forked from iThinker/async_v1.swift
Created February 27, 2017 20:32
Show Gist options
  • Save OctoberHammer/2298e179a7f2fd89e0e9e8784e565147 to your computer and use it in GitHub Desktop.
Save OctoberHammer/2298e179a7f2fd89e0e9e8784e565147 to your computer and use it in GitHub Desktop.
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