dispatch_after - GCD in Swift?

grand-central-dispatch, objective-c, swift

Solution

A clearer idea of the structure:

dispatch_after(when: dispatch_time_t, queue: dispatch_queue_t, block: dispatch_block_t?)

`dispatch_time_t` is a `UInt64`. The `dispatch_queue_t` is actually type aliased to an `NSObject`, but you should just use your familiar GCD methods to get queues. The block is a Swift closure. Specifically, `dispatch_block_t` is defined as `() -> Void`, which is equivalent to `() -> ()`.

Example usage:

let delayTime = dispatch_time(DISPATCH_TIME_NOW, Int64(1 * Double(NSEC_PER_SEC)))
dispatch_after(delayTime, dispatch_get_main_queue()) {
    print("test")
}

EDIT:

I recommend using @matt's really nice `delay` function.

EDIT 2:

In Swift 3, there will be new wrappers for GCD. See here: https://github.com/apple/swift-evolution/blob/master/proposals/0088-libdispatch-for-swift3.md

The original example would be written as follows in Swift 3:

let deadlineTime = DispatchTime.now() + .seconds(1)
DispatchQueue.main.asyncAfter(deadline: deadlineTime) {
    print("test")
}

Note that you can write the `deadlineTime` declaration as `DispatchTime.now() + 1.0` and get the same result because the `+` operator is overridden as follows (similarly for `-`):

- `func +(time: DispatchTime, seconds: Double) -> DispatchTime`

- `func +(time: DispatchWalltime, interval: DispatchTimeInterval) -> DispatchWalltime`

This means that if you don't use the `DispatchTimeInterval` `enum` and just write a number, it is assumed that you are using seconds.

Problem

I've gone through the iBook from Apple, and couldn't find any definition of it: Can someone explain the structure of `dispatch_after`? ``` dispatch_after(<#when: dispatch_time_t#>, <#queue: dispatch_queue_t?#>, <#block: dispatch_block_t?#>) ```

Original source

Related problems