Skip to content

Instantly share code, notes, and snippets.

@arashkashi
Last active June 25, 2019 22:17
Show Gist options
  • Save arashkashi/67bb71e56e199732f4a25fc6e609f9de to your computer and use it in GitHub Desktop.
Save arashkashi/67bb71e56e199732f4a25fc6e609f9de to your computer and use it in GitHub Desktop.
Pipeline operations
import UIKit
import Foundation
enum PipableOperationOutput<T> {
case success(T)
case fail(Error)
}
protocol PipableOpInput {
associatedtype Input
var input: Input? { get set }
}
protocol PipableOpOutput {
associatedtype Output
var output: PipableOperationOutput<Output>? { get set }
}
protocol PipableOperation: PipableOpInput, PipableOpOutput {
associatedtype Input
associatedtype Output
mutating func initInputWith(data: Input) -> Self
var dependencies: [Operation] { get }
var input: Input? { get set }
var output: PipableOperationOutput<Output>? { get set}
func getPrevOperation<T: PipableOpOutput>() -> T? where T.Output == Self.Input
mutating func loadInputFromPrevOperation<T: PipableOpOutput>(prevOperation: T) -> Bool where T.Output == Self.Input
}
extension PipableOperation where Self : Operation {
mutating func initInputWith(data: Input) -> Self {
self.input = input
return self
}
func getPrevOperation<T: PipableOpOutput>() -> T? where T.Output == Self.Input {
guard let valid = dependencies.first as? T else {
return nil
}
return valid
}
mutating func loadInputFromPrevOperation<T: PipableOpOutput>(prevOperation: T) -> Bool where T.Output == Self.Input {
if let valid = prevOperation.output {
switch valid {
case .fail( _): break
case .success(let result): input = result
}
return true
} else {
return false
}
}
}
final class Op1: Operation, PipableOperation {
var input: String?
var output: PipableOperationOutput<Bool>?
override func main() {
if input == "arash" {
output = .success(true)
print("Op1 true")
} else {
output = .success(false)
print("Op1 false")
}
}
}
final class Op2: Operation, PipableOperation {
typealias Input = Bool
typealias Output = String
var input: Bool?
var output: PipableOperationOutput<String>?
override func main() {
if let prev: Op1 = self.getPrevOperation(), let valid = prev.output {
switch valid {
case .success(let result): if result { print("op2 true")} else {
print("ob2 false")
}
case .fail(_): break
}
}
}
}
var op1 = Op1()
op1.initInputWith(data: "arash")
var op2 = Op2()
op2.addDependency(op1)
OperationQueue.main.addOperations([op1, op2], waitUntilFinished: false)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment