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

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

我试图 swift 做到这一点,它给错误。
func completionFunction(NSString* completionReason){ }
typealias CompletionBlock = completionFunction



定义 :
var completion: CompletionBlock = { }

这该怎么做?

更新:

根据@jtbandes的回答,我可以创建带有多个参数的闭包,例如
typealias CompletionBlock = ( completionName : NSString, flag : Int) -> ()

最佳答案

syntax for function types(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+起,仅需要在输入类型周围加上括号。

关于ios - swift : Closure declaration as like block declaration,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/24133797/

10-08 23:12