Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

swift : Closure declaration as like block declaration

Tags:

ios

swift

We can declare block as below in Objective-C.

typedef void (^CompletionBlock) (NSString* completionReason);

I'm trying to do this in swift, it give error.

func completionFunction(NSString* completionReason){ }
typealias CompletionBlock = completionFunction

Error : Use of undeclared 'completionFunction'

Definition :

var completion: CompletionBlock = { }

How to do this?

Update:

According to @jtbandes's answer, I can create closure with multiple arguments as like

typealias CompletionBlock = ( completionName : NSString, flag : Int) -> ()
like image 283
Mani Avatar asked Jun 10 '14 05:06

Mani


People also ask

What are the different types of closures 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.

What is a closure expression in Swift?

Closure expressions in Swift 4 language follow crisp, optimization, and lightweight syntax styles which includes. Inferring parameter and return value types from context. Implicit returns from single-expression closures.

What is the advantage of using closure in Swift?

According to the Apple Documentation, “Closures are self-contained blocks of functionality that can be passed around and used in your code”. Closures can capture and store references to any constants and variables from the context in which they are defined.


2 Answers

The syntax for function types is (in) -> out.

typealias CompletionBlock = (NSString?) -> Void
// or
typealias CompletionBlock = (result: NSData?, error: NSError?) -> Void
var completion: CompletionBlock = { reason in print(reason) }
var completion: CompletionBlock = { result, error in print(error) }

Note that the parentheses around the input type are only required as of Swift 3+.

like image 163
jtbandes Avatar answered Oct 20 '22 09:10

jtbandes


Here is awesome blog about swift closure.

Here are some examples:

As a variable:

var closureName: (inputTypes) -> (outputType)

As an optional variable:

var closureName: ((inputTypes) -> (outputType))?

As a type alias:

typealias closureType = (inputTypes) -> (outputType)
like image 22
BLC Avatar answered Oct 20 '22 11:10

BLC