0

I am new to swift 3.0 , i am facing issue in one little code snippet which is throwing error when i assign @escaping closure to nil as per attached screenshot:

ScreenShot and here is my code...

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

Can anyone please help me on this issue.
Thanks in advance.

muescha
  • 1,493
  • 2
  • 12
  • 22
Jay Bhadja
  • 30
  • 6

2 Answers2

2

Seems your issue is more of an Optional closure type than @escaping.

Try changing this line:

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

to:

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

()->()? represents a non-Optional closure which returns ()? (aka Optional<Void>), which may not be what you want.

OOPer
  • 44,179
  • 5
  • 90
  • 123
0

in swift 3 there is an other solution from 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()
Community
  • 1
  • 1
muescha
  • 1,493
  • 2
  • 12
  • 22