What does type ((Int) & # 8594; Int) mean in Swift?

I talked about implementing Apple in Swift and came across an example like this:

func makeIncrementer() -> ((Int) -> Int) { func addOne(number: Int) -> Int { return 1 + number } return addOne } var increment = makeIncrementer() increment(7) 

Can you explain the syntax of the return type of the makeIncrementer function? I understand that this function returns another function, but the role of ((Int) -> Int) in this context is not yet clear to me.

+6
source share
3 answers

This indicates that the function returns a function , and the returned function accepts Int as an input parameter and returns Int .

Defining functions inside functions in Swift is completely legal.

+7
source

(Int -> Int) means a closure (or function) that takes an Int parameter as a parameter and returns an Int .

The syntax for declaring a closure type is:

 (parameters) -> (return_types) 

parameters is a list of parameters that the closure accepts as input, and return_types is a list of values ​​returned by the closure. Both are tuples, but in the case of a single parameter or one type of return, the bracket identifying the tuple can be omitted. So, for example, clousure, expecting one parameter and returning one value, can be defined as:

 parameter -> return_type 

In your case:

 Int -> Int 

is a closure that has 1 input parameter of type Int and returns a Int

The return type is enclosed in parentheses so that it is clear what the return type is, but you can also write it as:

 func makeIncrementer() -> Int -> Int { 

This, in my opinion, is less readable than

 func makeIncrementer() -> (Int -> Int) { 
+2
source

I am not completely familiar with the swift syntax, but I think that all higher order functions work the same way. makeIncrementer is a function that:

  • accepts parameters no
  • returns a function that:
    • takes an Int parameter
    • returns Int

Visual explanation ( a -> b means a function that takes type a as a parameter and returns type b ):

  makeIncrementer -> (Int -> Int)
                            ^
                            |
                            |
                            a function that takes an Int and returns an Int,
                            ie (addOne in your case)

+1
source

Source: https://habr.com/ru/post/976632/


All Articles