等待后台线程随机时间

P3r*_*rry 3 swift

目前我正在使用它在调用函数之前在后台线程上等待 5 秒: DispatchQueue.global(qos: .background).asyncAfter(deadline: .now() + 5, execute: {

这很好用,但我想每次都等待一个随机的持续时间。做这样的事情:

let randomTime = Int(arc4random_uniform(10))
DispatchQueue.global(qos: .background).asyncAfter(deadline: .now() + randomTime, execute: {
Run Code Online (Sandbox Code Playgroud)

给我错误: Type of expression is ambiguous without more context

干杯。

Joe*_*Joe 5

试试下面的代码:

    let randomTime = Int(arc4random_uniform(10))

    DispatchQueue.main.asyncAfter(deadline: .now() + .seconds(randomTime)) {

    print("Delay is \(randomTime) sec")

        //Do something here  
    }
Run Code Online (Sandbox Code Playgroud)

您也可以使用.microseconds(Int).nanoseconds(Int)取决于您的要求。