Last active
May 18, 2018 09:12
-
-
Save filletofish/2eb689d356fb6a6f46981a04a1991bc7 to your computer and use it in GitHub Desktop.
Swift chaining completion Blocks
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 | |
protocol Performable { | |
associatedtype Input | |
associatedtype Output | |
var action: (Input) -> (Output) { get } | |
var completion: (Output) -> () { get } | |
func perform(data: Input) | |
} | |
struct Action<I, O> { | |
let action: (I) -> (O) | |
let completion: (O) -> () | |
} | |
extension Action: Performable { | |
typealias Input = I | |
typealias Output = O | |
func perform(data: Input) { | |
let output: Output = action(data) | |
completion(output) | |
} | |
func chain<P:Performable> (to anotherChain: P) -> Action<Input, P.Output> | |
where Output == P.Input | |
{ | |
return Action<Input, P.Output>(action: { input -> (P.Output) in | |
let firstOutput = self.action(input) | |
self.completion(firstOutput) | |
let secondOuput = anotherChain.action(firstOutput) | |
return secondOuput | |
}, completion: anotherChain.completion) | |
} | |
} | |
let client = Action<String, Int>(action: { string -> (Int) in | |
return Int(string)! | |
}) { someInt in | |
print(someInt) | |
} | |
let parser = Action<Int, Float>(action: { someInt -> (Float) in | |
return 11.0 | |
}) { someFloat in | |
print("Got here: \(someFloat)") | |
} | |
let chained = client.chain(to: parser) | |
chained.perform(data: "11") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
import Foundation
class Chainable<I, O> {
func perform(data: I, callback: (O)->()) {
}
//a = Chainable<Int, Double>()
//b = Chainable<Double, String>()
//c = Chainable<String, Float>()
//a-->b-->c
class Cleint<String, Data> {
func perform(a: String) {
DispatchQueue.main.async {
loaddata()
callback(data)
}
}
}