Swift - 闭包表达式语法

Swift - closure expression syntax

我正在使用 Alamofire 库,我注意到他们使用这种语法

func download(method: Alamofire.Method, URLString: URLStringConvertible, headers: [String : String]? = default, #destination: Alamofire.Request.DownloadFileDestination) -> Alamofire.Request

需要 4 个参数作为输入,但如果您转到 documentation 调用方法,他们会使用以下

Alamofire.download(.GET, "http://httpbin.org/stream/100") { temporaryURL, response in
let fileManager = NSFileManager.defaultManager()
if let directoryURL = fileManager.URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask)[0] as? NSURL {
    let pathComponent = response.suggestedFilename
    return directoryURL.URLByAppendingPathComponent(pathComponent!)
}
return temporaryURL}

只需要 2 个参数(method:URLString:)我认为参数 headers 是可选的,因为提供了 default 语句。 我不明白 Destination 是如何处理的。 你能解释一下关闭是如何处理的吗? 为什么花括号在方法调用之后打开而不是在 URLString param 之后的调用内?

非常感谢您提供的任何帮助

马可

这是尾随闭包技术

如果一个方法接受闭包作为最后一个参数

class Foo {
    func doSomething(number: Int, word: String, completion: () -> ()) {

    }
}

可以按照经典方式调用:

Foo().doSomething(1, word: "hello", completion: { () -> () in 
    // your code here
})

或者使用尾随闭包技术

Foo().doSomething(1, word: "hello") { () -> () in 
    // your code here
}

结果是一样的,只是语法更优雅(恕我直言)。