2017-03-28 53 views
3

目前我使用此等待在后台线程每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: { 

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

干杯。

+0

尝试使用'TimeInterval(arc4random_uniform(10))'代替。该错误意味着编译器不确定你想要做什么。但是我从来没有在这么简单的代码中看到这个错误。 – TheValyreanGroup

回答

2

试试下面的代码表示:

let randomTime = Int(arc4random_uniform(10)) 

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

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

     //Do something here 
    } 

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

+0

完美。谢谢! – P3rry

+0

DispatchQueue.main.asyncAfter(截止时间:.now()+ .seconds(randomTime))会抛出以下错误:“表达式的类型不明确,没有更多上下文” - 主要是以下语句中的+:.now()+ .seconds( randomTime) – iosforme

0

.now()返回一个DispatchTime类型。类似于

DispatchQueue.global(qos: .background).asyncAfter(deadline: DispatchTime(uptimeNanoseconds: [any_random_generator]...... 

应该这样做。注意,any_random_generator必须返回UINT64和时间在纳秒

0

望着文档的Dispatch,似乎有两个重载的+操作员会为你工作:

public func +(time: DispatchTime, interval: DispatchTimeInterval) -> DispatchTime 

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

我建议使用第二个函数并初始化的Double代替Int喜欢你”现在重试:

let randomTime = Double(arc4random_uniform(10)) 
相关问题