A Useful Shortcut for dispatch_after()

In Grand Central Dispatch, the dispatch_after() function is used to perform a block of code after a given delay.

It's a bit of a nuisance to calculate the "when" time though, so this shortcut is pretty useful:

import UIKit

func delay(delay: NSTimeInterval, _ block: dispatch_block_t) {
    
    let when = dispatch_time(
        DISPATCH_TIME_NOW,
        Int64(delay * Double(NSEC_PER_SEC))
    )
    
    dispatch_after(when, dispatch_get_main_queue(), block)
}

If you wanted to perform some action after 1.5 seconds, you would use this as follows:

delay(1.5) {
    // Do something
}

This will execute on the main queue, but you could obviously modify the code if you needed it to run on a different queue.