如何向 DispatchQueue 添加时间延迟变量

Ser*_*mer 0 grand-central-dispatch ios swift

首先我使用 arc4random 创建了一个 randomDelay 值

然后我想将 randomDelay 值添加到 DispatchQueue 以创建一个随机时间延迟变量

这是我的代码:

func animation1() {

UIView.animate(withDuration: 1, animations: {

    // various code

}, completion: { (true) in

    //delay calling the function by the randomDelay value of '0' to '2' seconds
    let randomDelay = arc4random_uniform(3)
    DispatchQueue.main.asyncAfter(deadline: .now() + randomDelay) { // the randomDelay value throws an unresolved identifier 'randomDelay' error
        self.showAnimation2() // Go to the next function
    }
  })
}
Run Code Online (Sandbox Code Playgroud)

谢谢

rma*_*ddy 5

您需要强制randomDelay转换为Double. 然后按如下方式使用它:

let randomDelay = arc4random_uniform(3)
DispatchQueue.main.asyncAfter(deadline: .now() + Double(randomDelay)) {
}
Run Code Online (Sandbox Code Playgroud)