Search code examples
xcodeswiftsyntaxclosuresalamofire

Swift - closure expression syntax


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


Solution

  • 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.