Swift: 与块声明类似的闭包声明

我们可以在 Objective-C 中声明下面的块。

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

我试着迅速地做这件事,但它会出错。

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

错误: 使用未声明的“补全函数”

定义:

var completion: CompletionBlock = { }

怎么做?

更新:

根据@jtbandes 的回答,我可以像这样用多个参数创建闭包

typealias CompletionBlock = ( completionName : NSString, flag : Int) -> ()
44747 次浏览

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)