What is the purpose of the two arrows in the user defined chooseStepFunction() in Swift?

前端 未结 3 541
孤城傲影
孤城傲影 2021-01-12 14:29

What do the double arrows indicate in the return type of the last function here?

Are they used to indicate two different return values?

If so, how do you kno

相关标签:
3条回答
  • 2021-01-12 15:11

    Notice that it's returning a function. So chooseStepFunction takes a bool and returns a function. The type signature of the function is (Int)->Int.

    An arrow indicates a function with the input parameter on the left side and the output on the right.

    0 讨论(0)
  • 2021-01-12 15:23

    The -> (Int) -> Int in

    func chooseStepFunction(backwards: Bool) -> (Int) -> Int{
    return backwards ? stepBackward: stepForward
    }
    

    means that the function returns a function that takes an Int as a parameter, and also returns an Int.

    You can see it as func chooseStepFunction(backwards: Bool) -> [ (Int) -> Int ] {

    0 讨论(0)
  • 2021-01-12 15:26

    Given:

    (x) -> (y) -> z
    

    You would read this as:

    A function which accepts x and returns a function which accepts y and returns z.

    So in this case, chooseStepFunction is a function that takes a bool and returns a function that takes an int and returns an int. This is right-associative, so you would read it as:

    (backwards: Bool) -> ((Int) -> Int)
    

    It's easiest to read this if you remember that the first set of parentheses (around Bool) aren't particularly special. They're just like the second set (around Int). (The parentheses aren't actually needed. (Int) -> Int is the same as Int -> Int.)

    Realizing this will help when you encounter currying:

    func addTwoNumbers(a: Int)(b: Int) -> Int
    

    This is really the same as:

    (a: Int) -> (b: Int) -> Int
    

    A function that takes an int and returns a function that takes an int and returns an int.

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