在早期版本的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
}