How does one make an optional closure in swift?

SwiftOptional Parameters

Swift Problem Overview


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.

Swift Solutions


Solution 1 - 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! 
    }
 }

Solution 2 - Swift

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.

Solution 3 - Swift

Since I assume, that this "optional" closure should simply do nothing, you could use a parameter with an empty closure as default value:

func then(onFulfilled: ()->(), onReject: ()->() = {}){       
    // now you can call your closures
    onFulfilled()
    onReject()
}

this function can now be called with or without the onReject callback

then({ ... })
then({ ... }, onReject: { ... })

No need for Swift's awesome Optionals? here!

Solution 4 - Swift

Maybe it's a cleaner way. Specially when the closure has complicated parameters.

typealias SimpleCallBack = () -> ()

class Promise {

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

}

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionMarcoscView Question on Stackoverflow
Solution 1 - SwiftCezarView Answer on Stackoverflow
Solution 2 - SwiftEvgeniiView Answer on Stackoverflow
Solution 3 - SwiftDiegoFringsView Answer on Stackoverflow
Solution 4 - SwiftSeifolahiView Answer on Stackoverflow