本文介绍了swift:Closure声明就像块声明一样的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我们可以在Objective-C中声明如下所示的块。
We can declare block as below in Objective-C.
typedef void (^CompletionBlock) (NSString* completionReason);
我试图在swift中执行此操作,它会给出错误。
I'm trying to do this in swift, it give error.
func completionFunction(NSString* completionReason){ }
typealias CompletionBlock = completionFunction
定义:
var completion: CompletionBlock = { }
如何做到这一点?
更新:
根据@ jtbandes的回答,我可以用多个参数如
According to @jtbandes's answer, I can create closure with multiple arguments as like
typealias CompletionBlock = ( completionName : NSString, flag : Int) -> ()
推荐答案
是(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) }
请注意,输入类型周围的括号仅在Swift 3 +时需要。
Note that the parentheses around the input type are only required as of Swift 3+.
这篇关于swift:Closure声明就像块声明一样的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!