ios swift : 闭包声明就像块声明一样
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/24133797/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
swift : Closure declaration as like block declaration
提问by Mani
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.
我正在尝试快速执行此操作,但会出错。
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) -> ()
回答by jtbandes
The syntax for function typesis (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+ 开始才需要。
回答by BLC
Hereis 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)