Author Topic: How do I create a delay in Swift?  (Read 3225 times)

kjmcneish

  • Administrator
  • *****
  • Posts: 719
    • View Profile
How do I create a delay in Swift?
« on: March 21, 2015, 04:00:54 PM »
Here's a nice little function from Matt Neuburg as posted on stack overflow:

Code: [Select]
func delay(delay:Double, closure:()->()) {
    dispatch_after(
        dispatch_time(
            DISPATCH_TIME_NOW,
            Int64(delay * Double(NSEC_PER_SEC))
        ),
        dispatch_get_main_queue(), closure)
}

You can call the function by passing the number of seconds you would like to delay. For example:

Code: [Select]
delay(1.0) {
  // do something
}

All the best!
Kevin McNeish
Author of Learn to Code in Swift: https://itunes.apple.com/us/book/learn-to-code-in-swift/id942956811?mt=11

« Last Edit: March 21, 2015, 04:45:30 PM by kjmcneish »