Swift-闭包表达式语法 [英] Swift - closure expression syntax
问题描述
我正在使用Alamofire库,我注意到他们使用了这种语法
i'm working with Alamofire library, i've noticed that they use this syntax
func download(method: Alamofire.Method, URLString: URLStringConvertible, headers: [String : String]? = default, #destination: Alamofire.Request.DownloadFileDestination) -> Alamofire.Request
需要4个参数作为输入,但是如果您转到文档调用他们使用以下方法的方法
that takes 4 parameters as input but if you go to the documentation to call the method they use the following
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个参数(方法:
和 URLString:
)我认为参数 headers
是可选的,因为提供了 default
语句。
我不明白目的地
的处理方式。
您能解释一下关闭的处理方式吗?
为什么在 URLString参数
之后在方法调用之后打开花括号而不在调用内部?
that takes only 2 parameters (method:
and URLString:
) i think that the param headers
is optional because provide the default
statement.
I don't understand how Destination
is handled.
Could you please explain me how the closure is handled?
Why the curl braces is open AFTER the method call and not inside the call after the URLString param
?
我非常感谢您可以提供的任何帮助
I really appreciate any help you can provide
Marco
推荐答案
这是尾随的闭包技术
如果方法接受闭包作为最后一个参数
It's the trailing closure technique
If a method accepts a closure as last param
class Foo {
func doSomething(number: Int, word: String, completion: () -> ()) {
}
}
您可以按照经典方式来称呼它:
You can call it following the classic way:
Foo().doSomething(1, word: "hello", completion: { () -> () in
// your code here
})
或使用尾随闭包技术:
Foo().doSomething(1, word: "hello") { () -> () in
// your code here
}
结果是同样,它只是一种更优雅的(IMHO)语法。
The result is the same, it just a more elegant (IMHO) syntax.
这篇关于Swift-闭包表达式语法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!