I was going through Apple\'s introduction to Swift and came across such example:
func makeIncrementer() -> ((Int) -> Int) {
func addOne(number: In
I am not exactly familiar with the syntax of swift, but I guess all higher-order functions work the same. makeIncrementer
is a function that:
Int
parameterInt
Visual explanation (a -> b
means a function that takes type a
as the parameter and returns type b
):
makeIncrementer -> (Int -> Int) ^ | | a function that takes an Int and returns an Int, i.e. (addOne in your case)
(Int -> Int)
denotes a closure (or function) taking an Int
as parameter and returning an Int
.
The syntax for declaring a closure type is:
(parameters) -> (return_types)
parameters
is a list of parameters the closure receives as input, and return_types
is the list of values the closure returns. Both are tuples, but in case of one parameter or one return type, the parenthesis identifying the tuple can be omitted. So for example a clousure expecting one parameter and returning one value can be defined as:
parameter -> return_type
In your case:
Int -> Int
is a closure having 1 input parameter of Int
type and returning a Int
The return type is enclosed in parenthesis to make it clear that's the return type, but you could also write it as:
func makeIncrementer() -> Int -> Int {
Which is in my opinion less readable than
func makeIncrementer() -> (Int -> Int) {
It indicates that the function returns a function and that returned function takes an Int
as an input parameter and returns an Int
as well.
Defining functions within functions is perfectly legal in Swift.