Marcosc Marcosc - 2 years ago 108
Swift Question

How does one make an optional closure in swift?

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 Source

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

func then(onFulfilled: ()->(), onReject: (()->())?){       
    if let callableRjector = onReject {
      // do stuff! 
    }
 }
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download