简体   繁体   中英

swift : Closure declaration as like block declaration

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) -> ()

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+.

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM