我正在使用 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
是可选的,因为提供了 默认
语句。
我不明白 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
}
结果是一样的,只是语法更优雅(恕我直言)。
关于xcode - Swift - 闭包表达式语法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32499461/