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.
It doesn't make sense to add escaping annotations to optional closures because they aren't function types: they are basically an enum (Optional) containing a function, the same way you would store a closure in any type: it's implicitly escaping because it's owned by another type.
As shown in the above table, there are three types of closures in Swift, namely global functions, nested functions, and closure expressions. They differ in several aspects, including their use scopes, their names, and whether they capture values, which will be discussed more in a later section.
Closures in Swift are similar to blocks in C and Objective-C and to lambdas in other programming languages. Closures can capture and store references to any constants and variables from the context in which they're defined. This is known as closing over those constants and variables.
If the last parameter to a function is a closure, Swift lets you use special syntax called trailing closure syntax. Rather than pass in your closure as a parameter, you pass it directly after the function inside braces.
You should enclose the optional closure in parentheses. This will properly scope the ?
operator.
func then(onFulfilled: ()->(), onReject: (()->())?){ if let callableRjector = onReject { // do stuff! } }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With