在早期版本的Swift中,可以使用以下代码创建延迟:

let time = dispatch_time(dispatch_time_t(DISPATCH_TIME_NOW), 4 * Int64(NSEC_PER_SEC))
dispatch_after(time, dispatch_get_main_queue()) {
    //put your code which should be executed with a delay here
}

但是现在,在Swift 3中,Xcode自动更改了6个不同的东西,但随后出现了以下错误:“不能转换DispatchTime。现在转换为期望值dispatch_time_t aka UInt64。”

在Swift 3中,如何在运行一段代码序列之前创建一个延迟?


当前回答

// x秒后运行函数

public static func runThisAfterDelay(seconds: Double, after: @escaping () -> Void) {
    runThisAfterDelay(seconds: seconds, queue: DispatchQueue.main, after: after)
}

public static func runThisAfterDelay(seconds: Double, queue: DispatchQueue, after: @escaping () -> Void) {
    let time = DispatchTime.now() + Double(Int64(seconds * Double(NSEC_PER_SEC))) / Double(NSEC_PER_SEC)
    queue.asyncAfter(deadline: time, execute: after)
}

/ /使用:-

runThisAfterDelay(seconds: x){
  //write your code here
}

其他回答

试试下面的延迟代码

//MARK: First Way

func delayForWork() {
    delay(3.0) {
        print("delay for 3.0 second")
    }
}

delayForWork()

// MARK: Second Way

DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) {
    // your code here delayed by 0.5 seconds
}

// x秒后运行函数

public static func runThisAfterDelay(seconds: Double, after: @escaping () -> Void) {
    runThisAfterDelay(seconds: seconds, queue: DispatchQueue.main, after: after)
}

public static func runThisAfterDelay(seconds: Double, queue: DispatchQueue, after: @escaping () -> Void) {
    let time = DispatchTime.now() + Double(Int64(seconds * Double(NSEC_PER_SEC))) / Double(NSEC_PER_SEC)
    queue.asyncAfter(deadline: time, execute: after)
}

/ /使用:-

runThisAfterDelay(seconds: x){
  //write your code here
}

一种方法是使用DispatchQueue.main.asyncAfter,正如很多人回答的那样。

另一种方法是使用perform(_:with:afterDelay:)。详情请点击这里

perform(#selector(delayedFunc), with: nil, afterDelay: 3)

@IBAction func delayedFunc() {
    // implement code
}

经过大量的研究,我终于明白了这一点。

DispatchQueue.main.asyncAfter(deadline: .now() + 2.0) { // Change `2.0` to the desired number of seconds.
   // Code you want to be delayed
}

这在Swift 3和Swift 4中创建了理想的“等待”效果。

受到这个答案的启发。

尝试以下在Swift 3.0及以上版本中实现的功能

func delayWithSeconds(_ seconds: Double, completion: @escaping () -> ()) {
    DispatchQueue.main.asyncAfter(deadline: .now() + seconds) { 
        completion()
    }
}

使用

delayWithSeconds(1) {
   //Do something
}