Created
December 30, 2015 11:48
-
-
Save Danappelxx/b345e31f4be178be3ea4 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
struct Task<Input, Output> { | |
typealias TaskExecutor = Input -> Output | |
let task: TaskExecutor? | |
var subTasks = [Task<Any,Any>]() | |
init(task: TaskExecutor? = nil) { | |
self.task = task | |
} | |
func run(input: Input) -> Output { | |
// if execute exists, run it | |
guard task == nil else { return task!(input) } | |
// if no subtasks, throw error | |
guard subTasks.count > 0 else { fatalError("Need to have at least one subtask") } | |
// get output of all subtasks | |
let output = subTasks.reduce(input as Any) { $1.run($0) } | |
// convert output to desired output type, otherwise throw error | |
guard let out = output as? Output else { fatalError("Output type mismatch") } | |
return out | |
} | |
func wrap() -> Task<Any,Any> { | |
// wrap Task<T,U> in Task<Any,Any> | |
return Task<Any,Any> { self.run($0 as! Input) } | |
} | |
} | |
func +=<T,U,V,W>(inout lhs: Task<T,U>, rhs: Task<V,W>) { | |
lhs.subTasks.append(rhs.wrap()) | |
} | |
func +<T,U,V,W>(lhs: Task<T,U>, rhs: Task<V,W>) -> Task<T,W>{ | |
var task = Task<T,W>() | |
task += lhs | |
task += rhs | |
return task | |
} | |
var reverse = Task<Int, Int>() | |
reverse += Task<Int, String> { String($0) } | |
reverse += Task<String, String> { String($0.characters.reverse()) } | |
reverse += Task<String, Int> { Int($0)! } | |
reverse.run(12345) // -> 54321 | |
var firstThreeDigits = Task<Int, Int>() | |
firstThreeDigits += Task<Int, String> { String($0) } | |
firstThreeDigits += Task<String, String> { $0[$0.startIndex..<$0.startIndex.advancedBy(3)] } | |
firstThreeDigits += Task<String, Int> { Int($0)! } | |
firstThreeDigits.run(12345) // -> 123 | |
var firstThreeDigitsOfReverseAndReversedAgain = reverse + firstThreeDigits + reverse | |
firstThreeDigitsOfReverseAndReversedAgain.run(12345) // -> 345 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment