Search code examples
iosswiftgrand-central-dispatch

What is the difference between these DispatchTime calculations?


I ran into this line code in AlamofireImage's older version.

let tinyDelay = DispatchTime.now() + Double(Int64(0.001 * Float(NSEC_PER_SEC))) / Double(NSEC_PER_SEC)

// Need to let the runloop cycle for the placeholder image to take affect
DispatchQueue.main.asyncAfter(deadline: tinyDelay) {
  self.run(imageTransition, with: image)
  completion?(response)
}

Why it is written that way when tinyDelay can be defined as below?

let tinyDelay = DispatchTime.now() + Double(0.001)

Solution

  • DispatchTime.now() + Double(Int64(0.001 * Float(NSEC_PER_SEC))) / Double(NSEC_PER_SEC)
    

    looks like a (bad) translation of the Objective-C code

    dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.001 * NSEC_PER_SEC));
    

    to Swift. The latter is a standard Objective-C code-snippet, but there no reason to make it so complicated in Swift. You can simply write

    let tinyDelay = DispatchTime.now() + 0.001
    

    or

    let tinyDelay = DispatchTime.now() + .milliseconds(1)