Tony Stark Tony Stark - 1 year ago 91
Swift Question

Are instance methods closures?

In the book, "Swift Programming Language 3.0", it mentioned that types of closure include:

Global functions are closures that have a name and do not capture
any values

Nested function are closures that have a name and can
capture values from their enclosing function

Closure expression are
unnamed closure written in a lightweight syntax that can capture
values from their surrounding context

I was just wondering does a function that exist in class scope count as a closure? One can certainly pass around such function as an argument to other function, but is it a closure?

Thanks in advance for any help!

Answer Source

Yes! Absolutely! Here's an example that uses the lowercased() method of String.

let aClosure: (String) -> () -> String = String.lowercased

let anUpperCasedString = "A B C"

let aLowerCaseString = aClosure(anUpperCasedString)()

You can see that the type of this closure is (String) -> () -> String. This is because String.lowercased is completely unapplied, it has no clue what instance it's operating on.

Calling aClosure(anUpperCasedString) will return a closure that's now () -> String. Baked into it is the instance it'll operate on. Only when you call this new closure with no params (()), will it actually execute the body of lowercased(), operating on the instance you gave it in the previous step, and return you the String result.

As a consequence, this is also valid:

let aLowerCaseString = String.lowercased("QWERTY")()

It just does all the steps above in one inlined step.

This technique is called function currying. This post talks more about this technique (called function currying) as it applies to instance methods in Swift.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download