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
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.
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 ] {
Given:
(x) -> (y) -> z
You would read this as:
A function which accepts
x
and returns a function which acceptsy
and returnsz
.
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.