Tony Stark Tony Stark - 29 days ago 7
iOS Question

does function in class scope count as a closure

In the book, "swift programming language 3.0", it mentioned that types of closure include:


Global functions are closure 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

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

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.

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.

Comments