gpt4 book ai didi

swift - 将函数重新格式化为 swift 3.0 语法

转载 作者:行者123 更新时间:2023-11-30 13:02:59 24 4
gpt4 key购买 nike

请注意,我没有创建此函数,它是库的一部分,尚未由其创建者更新。有人可以提供如何将功能切换到 swift 3.0 的建议吗?

func debounce( delay:TimeInterval, queue:DispatchQueue, action: @escaping (()->()) ) -> ()->() {
lastFireTime = dispatch_time(DISPATCH_TIME_NOW,0)
dispatch_after(dispatch_time(DISPATCH_TIME_NOW,dispatchDelay),queue) {
let now = dispatch_time(DISPATCH_TIME_NOW,0)
let when = dispatch_time(lastFireTime, dispatchDelay)
if now >= when {
action()
}
}

}
}

最佳答案

C API

dispatch_time_t
dispatch_time(dispatch_time_t base, int64_t offset);

void
dispatch_after(dispatch_time_t when, dispatch_queue_t queue,
void (^block)(void));

在 Swift 中,可以通过 Dispatch 框架(import Dispatch)获得相同的功能,这是一个构建在 C API 之上的优秀的面向对象框架。在 Playground 中尝试下一个片段,然后检查当前的 Apple documentation了解更多详情。

import PlaygroundSupport
PlaygroundPage.current.needsIndefiniteExecution = true

import Foundation
import Dispatch

let queue = DispatchQueue(label: "my queue")

// call the block asynchronously after some time
print(1, "now is", Date())

queue.asyncAfter(deadline: .now() + .seconds(5)) {
print()
print(3, "now is", Date())
PlaygroundPage.current.finishExecution()
}

print(2, "now is", Date())

初学者的良好起点是 here

我建议您阅读A quick look at Grand Central Dispatch and Swift 3以非常压缩的形式提供大量信息。

关于swift - 将函数重新格式化为 swift 3.0 语法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39715892/

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