Swift - closure expression syntax

你。 提交于 2019-12-10 22:46:19

问题


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

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}

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


回答1:


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
})

Or using the trailing closure technique:

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

The result is the same, it just a more elegant (IMHO) syntax.



来源:https://stackoverflow.com/questions/32499461/swift-closure-expression-syntax

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!