Vlad Dinu
Vlad Dinu

Reputation: 192

Syntax where let (constant) behaves like a function. Can you explain?

I came acros this syntax while trying to overwrite a file in Swift, but I can't understand it, since it seems that the constant behaves like a function (I'm using Alamofire for networking):

 let destination: (NSURL, NSHTTPURLResponse) -> (NSURL) = {
        (temporaryUrl, response)  in
        if response.statusCode == 200 {
            if NSFileManager.defaultManager().fileExistsAtPath(pdfUrl.path!) {
                try! NSFileManager.defaultManager().removeItemAtURL(pdfUrl)
            }
            return DocumentDirectoryUrl.URLByAppendingPathComponent(pdfFileName)
        }
        else {
            return temporaryUrl
        }
    }

Here are the constants used in destination

    let DocumentDirectoryUrl = NSURL(fileURLWithPath: NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true).first!)
    let pdfFileName = filename
    let pdfUrl = DocumentDirectoryUrl.URLByAppendingPathComponent(pdfFileName)

I don't understand how it's working because destination is declared as a constant, but it behaves like a function. Can someone explain it to me?

Upvotes: 0

Views: 94

Answers (1)

gnasher729
gnasher729

Reputation: 52632

In Swift, functions are objects, just like integers, doubles, strings, and so on. So yes, you can absolutely assign a function to a constant. So that constant doesn't have a type "Int" or "Double" or "String" but in this case "(NSURL, NSURLHTTPResponse) -> NSURL".

You can have an array of functions, a dictionary with functions as values, a struct or class where one or more instance variables are functions, and so on.

Upvotes: 2

Related Questions