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
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
Yes! Absolutely! Here's an example that uses the
lowercased() method of
let aClosure: (String) -> () -> String = String.lowercased let anUpperCasedString = "A B C" print(anUpperCasedString) let aLowerCaseString = aClosure(anUpperCasedString)() print(aLowerCaseString)
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.
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
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.