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

前端 未结 3 577
孤城傲影
孤城傲影 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: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.

提交回复
热议问题