如何在swift 3.0中返回void @escaping闭包?

时间:2017-01-21 07:39:43

标签: ios swift

我是swift 3.0的新手,我在一个小代码片段中遇到问题,当我按照附带的屏幕截图将@escaping的分配给nil时抛出错误:

ScreenShot 这是我的代码...

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;
}

任何人都可以帮我解决这个问题 提前谢谢。

2 个答案:

答案 0 :(得分:1)

似乎您的问题更多是可选闭包类型而不是@escaping

尝试更改此行:

var closure : ()->()? = closure

为:

var closure : (()->())? = closure

()->()?代表一个非可选的闭包,它返回()?(又名Optional<Void>),这可能不是你想要的。

答案 1 :(得分:0)

在swift 3中,solution

还有另一个david-lawson
let task = DispatchWorkItem { print("do something") }

// execute task in 2 seconds
DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 2, execute: task)

// optional: cancel task
task.cancel()