Search code examples
swiftoperator-overloadinginfix-notation

Creating an infix operator with a parameter


Currently, I'm trying to streamline background thread to main thread executions in my application.

The way I'm doing that is this:

import Foundation

infix operator ~> {}

private let queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0)

func ~> (backgroundClosure: () -> (), mainClosure: () -> ()) {
    dispatch_async(queue) {
        backgroundClosure()
        dispatch_async(dispatch_get_main_queue(), mainClosure)
    }
}

which would let me do something like:

{ println("executed in background thread") } ~> { println("executed in main thread") }

Now... I wanted to extend this functionality to potentially be able to dispatch_after to the main thread, so maybe I want it to be called 0.25 seconds later or something.

Is there a way to achieve this by passing in a parameter somehow?

Ideally, I'd be able to implement something like backgroundClosure ~>(0.25) mainClosure, but I doubt that is possible


Solution

  • Just a suggestion:

    infix operator ~> {}
    
    private let queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0)
    
    func ~> (backgroundClosure: () -> (), secondParam: (delayTime:Double, mainClosure: () -> () )) {
        // you can use the `delayTime` here
        dispatch_async(queue) {
            backgroundClosure()
            dispatch_async(dispatch_get_main_queue(), secondParam.mainClosure)
        }
    }
    

    How to use:

    { print("executed in background thread") } ~> (0.25, { print("executed in main thread") })