Skip to content

Instantly share code, notes, and snippets.

DispatchQueue.global().async {
let result = doSomething()
let transformedResult = transform(result)
completionHandler(transformedResult)
}
@sjordine
sjordine / DispatchQueue.swift
Last active July 24, 2018 17:13
DispatchQueue example
DispatchQueue.global().async {
let result = doSomething()
completionHandler(result)
}
DispatchQueue.global().async {
let result = doSomethingAsynchronously()
let transformedToAsyncFunction = transformToAsynchronous(result)
DispatchQueue.global().async {
let transformedValue = transformedToAsyncFunction()
completionHandler(transformedValue)
}
}
class Promise<T> {
var task:(() -> T)?
init(_ value: T) {
task = { return value }
}
init(_ task:@escaping() -> T) {
self.task = task
func map<Destination>(_ transform:@escaping(T)->Destination) -> Promise<Destination> {
return PromiseMap(container: self, transform: transform)
}
class PromiseMap<Source, Destination>: Promise<Destination> {
let sourcePromise: Promise<Source>
let transform: (Source)->(Destination)
init(container:Promise<Source>, transform: @escaping(Source)->Destination) {
self.sourcePromise = container
self.transform = transform
super.init()
}
originalPromise // that is the original Promise A
.map(transformFunction) // this function returns a new Promise B
.onCompletion {... // this onCompletion refers to Promise B
// so the Promise A onCompletion is not "exposed"
func flatMap<Destination>(_ transform:@escaping(T) -> Promise<Destination>) -> Promise<Destination> {
let mappedTransform = self.map(transform)
return NestedPromise(mappedTransform)
}
class NestedPromise<T>: Promise<T> {
var outerPromise:Promise<Promise<T>>
init(_ nestedPromises:Promise<Promise<T>>) {
outerPromise = nestedPromises
super.init()
}
override func onCompletion(_ completionHandler: @escaping (T) -> Void) {
let nasaURL = Promise("https://api.nasa.gov/planetary/apod?api_key=DEMO_KEY")
func imageURL(from urlString:String) -> URL {
let url = URL(string:urlString)!
let data = try! Data(contentsOf: url)
let jsonDictionary = try! JSONDecoder().decode([String:String].self, from: data)
let imageURL = jsonDictionary["hdurl"] as! String
return URL(string:imageURL)!
}