Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 374
Marcosc Avatar asked Jun 24 '14 20:06

Marcosc


People also ask

Why optional closures are escaping?

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.

How many types of closures are there in Swift?

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.

How does closure work in Swift?

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.

What is trailing closure syntax in Swift?

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.


1 Answers

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

func then(onFulfilled: ()->(), onReject: (()->())?){            if let callableRjector = onReject {       // do stuff!      }  } 
like image 139
Cezar Avatar answered Sep 21 '22 13:09

Cezar