What does the type ((Int) -> Int) mean in Swift?

后端 未结 3 1457
悲哀的现实
悲哀的现实 2021-01-12 07:01

I was going through Apple\'s introduction to Swift and came across such example:

func makeIncrementer() -> ((Int) -> Int) {

    func addOne(number: In         


        
相关标签:
3条回答
  • 2021-01-12 07:34

    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:

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

    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)
    
    
    0 讨论(0)
  • 2021-01-12 07:48

    (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) {
    
    0 讨论(0)
  • 2021-01-12 07:57

    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.

    0 讨论(0)
提交回复
热议问题