我是swift 3.0的新手,我在一个小代码片段中遇到问题,当我按照附带的屏幕截图将@escaping的分配给nil时抛出错误:
func delay(_ time:TimeInterval, closure: @escaping ()-> ()) -> dispatch_cancelable_closure?
{
func dispatch_later(_ clsr:@escaping ()->Void) {
DispatchQueue.main.asyncAfter(
deadline: DispatchTime.now() + Double(Int64(time * Double(NSEC_PER_SEC))) / Double(NSEC_PER_SEC), execute: clsr)
}
var closure : ()->()? = closure
var cancelableClosure:dispatch_cancelable_closure?
let delayedClosure:dispatch_cancelable_closure = { cancel in
if closure != nil {
if (cancel == false) {
DispatchQueue.main.async(execute: closure as! @convention(block) () -> Void);
}
}
closure = nil
cancelableClosure = nil
}
cancelableClosure = delayedClosure
dispatch_later {
if let delayedClosure = cancelableClosure {
delayedClosure(false)
}
}
return cancelableClosure;
}
任何人都可以帮我解决这个问题 提前谢谢。
答案 0 :(得分:1)
似乎您的问题更多是可选闭包类型而不是@escaping
。
尝试更改此行:
var closure : ()->()? = closure
为:
var closure : (()->())? = closure
()->()?
代表一个非可选的闭包,它返回()?
(又名Optional<Void>
),这可能不是你想要的。
答案 1 :(得分:0)
在swift 3中,solution
还有另一个david-lawsonlet task = DispatchWorkItem { print("do something") }
// execute task in 2 seconds
DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 2, execute: task)
// optional: cancel task
task.cancel()