【问题标题】:Creating an infix operator with a parameter使用参数创建中缀运算符
【发布时间】:2015-10-14 22:11:53
【问题描述】:

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

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

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 之类的东西,但我怀疑这是可能的

【问题讨论】:

    标签: swift operator-overloading infix-notation


    【解决方案1】:

    只是一个建议:

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

    【讨论】:

    • 哦,这其实是个好主意。我试试看。
    【解决方案2】:

    试试这个:

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

    【讨论】:

      猜你喜欢
      • 2014-07-16
      • 1970-01-01
      • 1970-01-01
      • 2021-06-18
      • 2021-05-10
      • 1970-01-01
      • 1970-01-01
      • 2016-01-26
      • 1970-01-01
      相关资源
      最近更新 更多