swiftgrand-central-dispatchdispatch-after

How does DispatchQueue.main.asyncAfter(deadline: .now() + 5.0) work in Swift 3?


In Swift 3 the syntax of GCD has changed quite a bit.

A call to dispatch_after() now looks like this:

DispatchQueue.main.asyncAfter(deadline: .now() + 5.0) {//do something}

That code would invoke the block 5 seconds after it's called.

How does that work? The docs say that the deadline parameter is a dispatch_time_t, which is a typealias for UInt64. I assume it's a mach time in nanoseconds. However, the .now() + delay syntax is adding decimal seconds to the value. Doesn't DispatchTime.now() return a UInt64 ? If so, adding decimal seconds to that should not work. If anything, I would expect the value added to .now() to be treated as nanoseconds, which would not be very useful.

(In swift 2 you used to have to multiply the value by a constant for the number of nanoseconds per second.)


Solution

  • OK, I found the answer to my own question in this thread:

    How do I write dispatch_after GCD in Swift 3?

    Apparently there is an override of the + operator that takes a DispatchTime and a double, treats the double as decimal seconds, and returns a resulting DispatchTime.