创建带参数的中缀运算符

Creating an infix operator with a parameter

目前,我正在尝试在我的应用程序中将后台线程简化为主线程执行。

我这样做的方式是这样的:

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)
    }
}

这会让我做类似的事情:

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

现在...我想扩展此功能以可能 dispatch_after 到主线程,所以也许我希望它在 0.25 秒后或其他时间被调用。

有没有办法通过某种方式传入参数来实现这一点?

理想情况下,我能够实现类似 backgroundClosure ~>(0.25) mainClosure 的东西,但我怀疑这是否可行

试试这个:

private let queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0)

infix operator ~>{ associativity left precedence 140}

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

只是一个建议:

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)
    }
}

使用方法:

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