[英]swift : Closure declaration as like block declaration
We can declare block as below in Objective-C. 我们可以在Objective-C中声明如下所示的块。
typedef void (^CompletionBlock) (NSString* completionReason);
I'm trying to do this in swift, it give error. 我试图在swift中做到这一点,它给出了错误。
func completionFunction(NSString* completionReason){ }
typealias CompletionBlock = completionFunction
Error : Use of undeclared 'completionFunction'
错误:使用未声明的'completionFunction'
Definition : 定义:
var completion: CompletionBlock = { }
How to do this? 这该怎么做?
Update: 更新:
According to @jtbandes's answer, I can create closure with multiple arguments as like 根据@ jtbandes的回答,我可以创建具有多个参数的闭包
typealias CompletionBlock = ( completionName : NSString, flag : Int) -> ()
The syntax for function types is (in) -> out
. 函数类型的语法是
(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+. 请注意,输入类型周围的括号仅在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)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.