简体   繁体   中英

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 :

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. 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 .

This is what you want in 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
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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