How does one make an optional closure in swift?
You should enclose the optional closure in parentheses. This will properly scope the ?
operator.
func then(onFulfilled: ()->(), onReject: (()->())?){
if let callableRjector = onReject {
// do stuff!
}
}
To make the code even shorter we can use nil
as default value for onReject
parameter and optional chaining ?()
when calling it:
func then(onFulfilled: ()->(), onReject: (()->())? = nil) {
onReject?()
}
This way we can omit onReject
parameter when we call then
function.
then({ /* on fulfilled */ })
We can also use trailing closure syntax to pass onReject
parameter into then
function:
then({ /* on fulfilled */ }) {
// ... on reject
}
Here is a blog post about it.