0

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.

Nitish
  • 13,845
  • 28
  • 135
  • 263

1 Answers1

8

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
}
Milan Nosáľ
  • 19,169
  • 4
  • 55
  • 90