How does one make an optional closure in swift?

Marcosc picture Marcosc · Jun 24, 2014 · Viewed 30.3k times · Source

I'm trying to declare an argument in Swift that takes an optional closure. The function I have declared looks like this:

class Promise {

 func then(onFulfilled: ()->(), onReject: ()->()?){       
    if let callableRjector = onReject {
      // do stuff! 
    }
 }

}

But Swift complains that "Bound value in a conditional must be an Optional type" where the "if let" is declared.

Answer

Cezar picture Cezar · Jun 24, 2014

You should enclose the optional closure in parentheses. This will properly scope the ? operator.

func then(onFulfilled: ()->(), onReject: (()->())?){       
    if let callableRjector = onReject {
      // do stuff! 
    }
 }