2

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

Eric Aya
  • 69,473
  • 35
  • 181
  • 253
Duncan C
  • 128,072
  • 22
  • 173
  • 272

1 Answers1

2

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.

Community
  • 1
  • 1
Duncan C
  • 128,072
  • 22
  • 173
  • 272
  • If you command-click on the `+` in Xcode then you'll see the declaration. – Martin R Nov 17 '16 at 18:28
  • @MartinR, thanks for the suggestion. In order to do that it would have had to occur to me that it was an override of the `+` operator that was doing it. – Duncan C Nov 17 '16 at 19:23
  • It seems to me we need a form of this call that takes a delay value, not a time relative to the current Mach time, since that's likely the most common form used by application developers. It would be a pretty simple extension, but it should be built in. – Duncan C Nov 17 '16 at 19:25