简体   繁体   English

将DispatchTime作为参数传递给DispatchAfter

[英]Pass DispatchTime as an argument in DispatchAfter

There is some old code I am processing. 我正在处理一些旧代码。 Following are two lines (old code) which I am not able to convert or rather understand : 以下是两行代码(旧代码),我无法转换或无法理解:

let dispatchTime = dispatch_time(dispatch_time_t(DispatchTime.now()), Int64(seconds * Double(NSEC_PER_SEC)))  
dispatch_after(dispatchTime, dispatch_get_main_queue(), block)  

Now, to make it work in Swift 4.x , this is what I did for line 1 : 现在,要使其在Swift 4.x中工作,这就是我对第1行所做的:

let dispatchTime =  DispatchTime(uptimeNanoseconds: UInt64(Int64(seconds * Double(NSEC_PER_SEC))))  

I made this conversion on the basis of initialiser description as mentioned here : 我根据此处提到的初始化程序描述进行了此转换:

Creates a time relative to the system clock that ticks since boot. 创建相对于系统时钟的时间,该时间自引导以来开始计时。

Since they say that it creates a relative time , DispatchTime.now() is already considered. 由于他们说它创建了一个相对时间 ,因此已经考虑了DispatchTime.now() Not to mention, I might be wrong. 更不用说,我可能是错的。 Please do correct me. 请纠正我。

For the second line, I am unaware as to how to pass DispatchTime as an argument in DispatchAfter . 对于第二个线,我不知道对如何通过DispatchTime作为一个参数DispatchAfter

This is what you want in Swift 3+: 这是您在Swift 3+中想要的:

let seconds = 2.0
// dispatchTime 2 seconds from now:
let dispatchTime: DispatchTime = DispatchTime.now() + seconds
DispatchQueue.main.asyncAfter(deadline: dispatchTime) {
    // code to be executed
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM