gpt4 book ai didi

swift - 创建带参数的中缀运算符

转载 作者:搜寻专家 更新时间:2023-11-01 07:30:02 25 4
gpt4 key购买 nike

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

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

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("在后台线程中执行") } ~> { println("在主线程中执行") }

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

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

理想情况下,我能够实现类似backgroundClosure ~>(0.25) 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") })

关于swift - 创建带参数的中缀运算符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33136492/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com